0
0
JUnittesting~10 mins

verify() for interaction verification in JUnit - Test Execution Trace

Choose your learning style9 modes available
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.

Test Code - JUnit with Mockito
JUnit
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");
    }
}
Execution Trace - 6 Steps
StepActionSystem StateAssertionResult
1Test startsJUnit test runner initializes-PASS
2Creates mock UserRepository objectmockRepo is a mock instance with no real behavior-PASS
3Creates UserService with mockRepoUserService instance ready with mock dependency-PASS
4Calls addUser("Alice") on UserServiceInside addUser, calls mockRepo.save("Alice")-PASS
5Verifies mockRepo.save("Alice") was called onceMockito checks recorded calls on mockRepoverify(mockRepo, times(1)).save("Alice") confirms one callPASS
6Test ends successfullyTest passed with no errors-PASS
Failure Scenario
Failing Condition: mockRepo.save("Alice") is not called or called more than once
Execution Trace Quiz - 3 Questions
Test your understanding
What does the verify() method check in this test?
AThat addUser returns a value
BThat UserService constructor runs without error
CThat mockRepo.save("Alice") was called exactly once
DThat mockRepo is not null
Key Result
Use verify() to check that your code interacts correctly with dependencies, ensuring expected methods are called the right number of times.