How to verify values passed to a mocked method?

 In this tutorial we will learn how we can verify values passed to a method.

Many times we want to verify values passed to a method while execution of the method being tested. This situation may arise when invoked method has no effect on the calling method. Eg. Publishing an event.

Let's take a look at the following example, where the `updateBalance()` method is calling `NotificationService` method to publish an event.

AccountService.java

public class AccountService {
    private final NotificationService notificationService;

    public void updateBalance(String accountNumber, BigDecimal newBalance) {
        // some calculations
        notificationService.publish(new AccountUpdatedEvent(accountNumber, newBalance));
    }
}


NotificationService.java

public class NotificationService {

    /**
     * Publish an event to the message broker
     *
     * @param event
     */
    public void publish(Event event) {
        // logic here to write to message broker
    }
}

Now if we want to test that an AccountUpdateEvent, containing correct account number and balance is being passed to the NotificationService, we can use ArgumentCaptor.

AccountServiceTest.java

@ExtendWith(MockitoExtension.class)
class AccountServiceTest {

    @Captor
    private ArgumentCaptor<AccountUpdatedEvent> accountUpdatedEventCaptor;

    @Mock
    private NotificationService notificationService;

    @InjectMocks
    private AccountService accountService;

    @Test
    void verify_update_event() {
        final String accountNumber = "636636636";
        final BigDecimal newBalance = BigDecimal.valueOf(1000000L);

        accountService.updateBalance(accountNumber, newBalance);

        Mockito.verify(notificationService).publish(accountUpdatedEventCaptor.capture());

        AccountUpdatedEvent accountUpdatedEvent = accountUpdatedEventCaptor.getValue();
        Assertions.assertEquals(accountNumber, accountUpdatedEvent.getAccountNumber());
        Assertions.assertEquals(newBalance, accountUpdatedEvent.getBalance());
    }

}


Full source code can be found on Github.


0 comments:

Post a Comment