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 |