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.
verify() for interaction verification in 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.
login was called with username "user1" and password "pass123".verify(userService).login("user1", "pass123");
sendEmail was called exactly two times with any string argument.verify(emailSender, times(2)).sendEmail(anyString());deleteUser was never called with any integer argument.verify(database, never()).deleteUser(anyInt());
This test creates a fake UserRepository and checks that when register is called, the saveUser method is called with the username "alice".
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"); } }
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.
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.
Practice
verify() in JUnit testing with mocks?Solution
Step 1: Understand the role of
verify()verify()is used to check interactions with mock objects, specifically if certain methods were called.Step 2: Differentiate from other mock-related actions
Creating mocks is done bymock(), asserting return values is done byassertEquals(), and initializing data is unrelated toverify().Final Answer:
To check if a method was called on a mock object -> Option BQuick Check:
verify() checks method calls = B [OK]
- Confusing verify() with mock() creation
- Using verify() to check return values
- Thinking verify() initializes test data
save() was called exactly once on a mock object repository?Solution
Step 1: Recall correct verify() syntax
The correct syntax usesverify(mockObject, times(n)).method()to check method call count.Step 2: Match options to syntax
verify(repository, times(1)).save(); matches the correct syntax. Options B, C, and D use invalid or non-existent methods.Final Answer:
verify(repository, times(1)).save(); -> Option CQuick Check:
verify(mock, times(1)).method() = A [OK]
- Writing times(1) after method call
- Passing call count as method argument
- Using non-existent verify methods
MyService service = mock(MyService.class); service.process(); verify(service, times(2)).process();
Solution
Step 1: Count method calls on mock
The methodprocess()is called once onservice.Step 2: Check verify() expectation
The verify expectsprocess()to be called twice (times(2)), but it was called once.Final Answer:
Test fails because process() was called only once -> Option AQuick Check:
verify times(2) but called once = D [OK]
- Assuming verify ignores call count
- Confusing times(2) with atLeast(2)
- Thinking one call satisfies times(2)
List<String> list = mock(List.class);
verify(list).add("item");
list.add("item");Solution
Step 1: Understand verify() checks past calls
verify()checks if a method was called before it is invoked.Step 2: Check order of calls
Here,verify()is called beforelist.add("item"), so no call happened yet to verify.Final Answer:
verify() is called before the method call on the mock -> Option DQuick Check:
verify() must follow method call [OK]
- Calling verify() before method invocation
- Assuming verify() can predict future calls
- Ignoring call order in tests
updateStatus(String status) was called exactly once with argument "ACTIVE" on a mock userService. Which code snippet correctly achieves this?Solution
Step 1: Use verify() with times(1) for exact call count
To check exactly one call, usetimes(1)in verify.Step 2: Match method call with exact argument
Pass the exact argument "ACTIVE" inside the method call in verify.Step 3: Evaluate options
verify(userService, times(1)).updateStatus("ACTIVE"); matches both call count and argument. verify(userService).updateStatus(anyString()); allows any string, not exact. verify(userService, times(1)).updateStatus(); misses argument. verify(userService, times(1)).updateStatus(anyString()); usestimes(1)butanyString()matches any argument, not specifically "ACTIVE".Final Answer:
verify(userService, times(1)).updateStatus("ACTIVE"); -> Option AQuick Check:
verify with times(1) and exact arg = C [OK]
- Using anyString() instead of exact argument
- Omitting times(1) for call count
- Calling verify() without arguments
Ready to prove it?
Pass the test and this pattern moves unknown
