Search code examples
javaspring-bootunit-testingjunit

Unit test to check a value that gets returned from a private method


I have these two methods in my Java class:

public CancelOrder generateCancelOrder(
  final CurrentState currentState,
  final Contract contract) {

    Context ctx = new Context();
    ctx.setVariable(
        ORDER_STATE_NOW, trans(currentState, contract));

    PennyOrderDetails pennyCancelOrderDetails =
        pennyCancelOrderService.requestCancelOrder(ctx);

    return CancelOrderResponse.builder()
        .premiumSummary(pennyCancelOrderDetails.getOrderSummary())
        .build();
}

private QuoteMessageCurrentState transform(
  final CurrentState currentState, final Contract contract) {
return QuoteMessageCurrentState.builder()
    .fromRequest(messageTemplateChanges.change(currentState, contract))
    .extras(
        VoluntaryExtras.calculateVoluntaryExtrasAmount(currentState.getVoluntaryExtras()))
    .build();
}

extras is a string value. Is there any way I can unit test this that I can confirm what that value is so as to ensure a value is returned for this and that it is the correct value?

I'm aware that private methods shouldn't be unit tested. I recently encountered an issue where the line .extras(VoluntaryExtras.calculateVoluntaryExtrasAmount(currentState.getVoluntaryExtras())) was missing but it wasn't picked up until an an issue was detected by a downstream application. I'd like to put something in place where if this was accidentally removed, it would not go unnoticed.


Solution

  • I added a test check that VoluntaryExtras.calculateVoluntaryExtrasAmount(currentState.getVoluntaryExtras() was called once when generateCancelOrder() was run.