Skip to main content

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.

public class AccountService {
    private final NotificationService notificationService;

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

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.

class AccountServiceTest {

    private ArgumentCaptor<AccountUpdatedEvent> accountUpdatedEventCaptor;

    private NotificationService notificationService;

    private AccountService accountService;

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

        accountService.updateBalance(accountNumber, newBalance);


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


Full source code can be found on Github.