0
0
JUnittesting~5 mins

verify() for interaction verification in JUnit

Choose your learning style9 modes available
Introduction

We use verify() to check if a specific action happened in our code, like a button click or a method call. It helps us confirm that parts of our program work together correctly.

When you want to check if a method was called on a mock object during a test.
When you need to confirm that a user interaction triggered the right backend call.
When you want to ensure a service was called exactly once or a certain number of times.
When you want to test that no unexpected interactions happened with a mock.
When you want to verify the order of method calls between objects.
Syntax
JUnit
verify(mockObject).methodName(arguments);

mockObject is the fake object you created to watch interactions.

methodName(arguments) is the method you expect to be called with specific arguments.

Examples
Check if login was called with username "user1" and password "pass123".
JUnit
verify(userService).login("user1", "pass123");
Check if sendEmail was called exactly two times with any string argument.
JUnit
verify(emailSender, times(2)).sendEmail(anyString());
Check that deleteUser was never called with any integer argument.
JUnit
verify(database, never()).deleteUser(anyInt());
Sample Program

This test creates a fake UserRepository and checks that when register is called, the saveUser method is called with the username "alice".

JUnit
import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;

class UserServiceTest {

    interface UserRepository {
        void saveUser(String username);
    }

    class UserService {
        private UserRepository repo;
        UserService(UserRepository repo) { this.repo = repo; }
        void register(String username) {
            repo.saveUser(username);
        }
    }

    @Test
    void testRegisterCallsSaveUser() {
        UserRepository mockRepo = mock(UserRepository.class);
        UserService service = new UserService(mockRepo);

        service.register("alice");

        verify(mockRepo).saveUser("alice");
    }
}
OutputSuccess
Important Notes

Always create mocks for the objects you want to watch interactions on.

If verify() fails, the test will fail and tell you which method call was missing or incorrect.

You can use times(n), never(), and other options to control how many times a method should be called.

Summary

verify() checks if a method was called on a mock object during a test.

It helps confirm that parts of your code interact as expected.

Use it to check method calls, call counts, and argument values.