Test Overview
This test checks that a method on a mock object is called exactly once during the test. It verifies interaction with a dependency using verify() from Mockito.
This test checks that a method on a mock object is called exactly once during the test. It verifies interaction with a dependency using verify() from Mockito.
import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; class UserService { private final UserRepository repo; UserService(UserRepository repo) { this.repo = repo; } void addUser(String name) { repo.save(name); } } interface UserRepository { void save(String name); } public class UserServiceTest { @Test void testAddUserCallsSave() { UserRepository mockRepo = mock(UserRepository.class); UserService service = new UserService(mockRepo); service.addUser("Alice"); verify(mockRepo, times(1)).save("Alice"); } }
| Step | Action | System State | Assertion | Result |
|---|---|---|---|---|
| 1 | Test starts | JUnit test runner initializes | — | PASS |
| 2 | Creates mock UserRepository object | mockRepo is a mock instance with no real behavior | — | PASS |
| 3 | Creates UserService with mockRepo | UserService instance ready with mock dependency | — | PASS |
| 4 | Calls addUser("Alice") on UserService | Inside addUser, calls mockRepo.save("Alice") | — | PASS |
| 5 | Verifies mockRepo.save("Alice") was called once | Mockito checks recorded calls on mockRepo | verify(mockRepo, times(1)).save("Alice") confirms one call | PASS |
| 6 | Test ends successfully | Test passed with no errors | — | PASS |
verify() in JUnit testing with mocks?verify()verify() is used to check interactions with mock objects, specifically if certain methods were called.mock(), asserting return values is done by assertEquals(), and initializing data is unrelated to verify().save() was called exactly once on a mock object repository?verify(mockObject, times(n)).method() to check method call count.MyService service = mock(MyService.class); service.process(); verify(service, times(2)).process();
process() is called once on service.process() to be called twice (times(2)), but it was called once.List<String> list = mock(List.class);
verify(list).add("item");
list.add("item");verify() checks if a method was called before it is invoked.verify() is called before list.add("item"), so no call happened yet to verify.updateStatus(String status) was called exactly once with argument "ACTIVE" on a mock userService. Which code snippet correctly achieves this?times(1) in verify.times(1) but anyString() matches any argument, not specifically "ACTIVE".Pass the test and this pattern moves unknown