Mock objects in JUnit - Build an Automation Script
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @ExtendWith(MockitoExtension.class) public class UserServiceTest { @Mock private UserRepository userRepository; @InjectMocks private UserService userService; @Test void testCreateUserCallsSave() { // Arrange User user = new User("Alice", "alice@example.com"); // Act userService.createUser(user); // Assert verify(userRepository, times(1)).save(user); verifyNoMoreInteractions(userRepository); } } // Supporting classes for context class User { private String name; private String email; public User(String name, String email) { this.name = name; this.email = email; } // equals and hashCode should be overridden for correct verification @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; User user = (User) o; return name.equals(user.name) && email.equals(user.email); } @Override public int hashCode() { return java.util.Objects.hash(name, email); } } interface UserRepository { void save(User user); } class UserService { private final UserRepository userRepository; public UserService(UserRepository userRepository) { this.userRepository = userRepository; } public void createUser(User user) { userRepository.save(user); } }
This test uses JUnit 5 with Mockito to check that UserService.createUser calls UserRepository.save exactly once with the correct User object.
Annotations: @Mock creates a mock UserRepository. @InjectMocks injects this mock into UserService.
Test steps: We create a User object, call createUser, then verify the mock's save method was called once with that user.
Verification: verify(userRepository, times(1)).save(user) checks the call count and argument. verifyNoMoreInteractions ensures no other calls happened.
Supporting classes: User overrides equals and hashCode so Mockito can compare objects correctly.
Now add data-driven testing with 3 different User inputs to verify save is called correctly each time
Practice
mock objects in JUnit testing?Solution
Step 1: Understand the role of mock objects
Mock objects imitate real objects to isolate the code being tested and control responses.Step 2: Identify the main benefit in testing
This helps test code without relying on actual implementations or external systems.Final Answer:
To simulate real objects and control their behavior during tests -> Option BQuick Check:
Mock objects = simulate and control behavior [OK]
- Thinking mocks speed up compilation
- Confusing mocks with test data generators
- Believing mocks replace the JUnit framework
Solution
Step 1: Recall Mockito syntax for creating mocks
Mockito usesmock(Class.class)to create mock objects.Step 2: Match the syntax to options
MyClass mock = mock(MyClass.class); matches the correct syntax:MyClass mock = mock(MyClass.class);Final Answer:
MyClass mock = mock(MyClass.class); -> Option AQuick Check:
Mockito mock creation = mock(Class.class) [OK]
- Using new Mock<>() which is not valid
- Calling mock() on an instance
- Using createMock which is not Mockito syntax
result be after execution?List<String> mockList = mock(List.class); when(mockList.size()).thenReturn(5); int result = mockList.size();
Solution
Step 1: Understand the mock setup
The mock list'ssize()method is stubbed to return 5 when called.Step 2: Evaluate the method call
CallingmockList.size()returns 5 as per the stub, not the real list size.Final Answer:
5 -> Option AQuick Check:
Stubbed method returns set value 5 [OK]
- Expecting default 0 for int return
- Thinking mock calls throw exceptions by default
- Confusing mock with real object behavior
MyService service = mock(MyService.class);
when(service.getData()).thenReturn("data");
verify(service).getData();Solution
Step 1: Understand verify usage in Mockito
Verification checks if a method was called on the mock during the test.Step 2: Check if method was called before verify
The code never callsservice.getData()beforeverify, so verification fails.Final Answer:
Missing call toservice.getData()before verify -> Option DQuick Check:
Verify requires method call before checking [OK]
- Verifying without calling the method
- Confusing mock creation syntax
- Thinking verify only works on void methods
getValue()?Solution
Step 1: Recall Mockito chaining for multiple returns
Mockito allows chainingthenReturn()calls to specify sequential return values.Step 2: Match chaining syntax to options
when(mock.getValue()).thenReturn("first").thenReturn("second");matches the correct chaining syntax for sequential calls.Final Answer:
when(mock.getValue()).thenReturn("first").thenReturn("second"); -> Option CQuick Check:
Chain thenReturn() for multiple call returns [OK]
- Passing multiple values in one thenReturn() call
- Overwriting stubs instead of chaining
- Reversing the order of return values
Ready to prove it?
Pass the test and this pattern moves unknown
