@Mock annotation in JUnit - Build an Automation Script
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; class UserServiceTest { @Mock private UserRepository userRepository; @InjectMocks private UserService userService; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); } @Test void testGetUserNameReturnsStubbedValue() { // Arrange when(userRepository.findUserNameById(1)).thenReturn("Alice"); // Act String result = userService.getUserName(1); // Assert assertEquals("Alice", result, "The service should return the stubbed user name"); verify(userRepository, times(1)).findUserNameById(1); } } // Supporting classes interface UserRepository { String findUserNameById(int id); } class UserService { private final UserRepository userRepository; UserService(UserRepository userRepository) { this.userRepository = userRepository; } String getUserName(int id) { return userRepository.findUserNameById(id); } }
This test class demonstrates how to use the @Mock annotation to create a mock of UserRepository. The @InjectMocks annotation injects this mock into the UserService instance.
In the setUp method, MockitoAnnotations.openMocks(this) initializes the mocks before each test.
The test method testGetUserNameReturnsStubbedValue stubs the repository method findUserNameById to return "Alice" when called with 1.
Then it calls the service method and asserts the returned value matches the stubbed value. It also verifies the repository method was called exactly once.
This setup ensures the service behavior is tested in isolation from the real repository, using the mock created by @Mock.
Now add data-driven testing with 3 different user IDs and expected names
Practice
@Mock annotation in JUnit testing?Solution
Step 1: Understand the role of
The@Mock@Mockannotation is used to create fake objects that imitate real dependencies in tests.Step 2: Identify the purpose in testing context
This helps isolate the code being tested from external systems or complex objects.Final Answer:
To create fake objects that simulate real dependencies for testing -> Option AQuick Check:
@Mockcreates fake objects [OK]
- Thinking @Mock runs tests in parallel
- Confusing @Mock with test report generation
- Assuming @Mock connects to real databases
@Mock in a JUnit 5 test class?Solution
Step 1: Check correct syntax for @Mock field declaration
The mock object should be declared as a private field with the @Mock annotation and no initialization.Step 2: Identify the correct option
@Mock private MyService service; correctly declares:@Mock private MyService service;without initializing it.Final Answer:
@Mock private MyService service; -> Option AQuick Check:
Declare mock as private field without initialization [OK]
- Initializing mock objects manually
- Using @Mock on methods instead of fields
- Declaring mocks as public or with invalid syntax
service.getData() when called inside the test?import static org.mockito.Mockito.*;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
class MyServiceTest {
@Mock
MyService service;
@Test
void testGetData() {
MockitoAnnotations.openMocks(this);
when(service.getData()).thenReturn("mocked data");
System.out.println(service.getData());
}
}Solution
Step 1: Understand mock initialization
The call toMockitoAnnotations.openMocks(this)initializes the@Mockannotated fields.Step 2: Analyze the stubbed method behavior
The linewhen(service.getData()).thenReturn("mocked data")sets the mock to return "mocked data" whengetData()is called.Final Answer:
mocked data -> Option DQuick Check:
Stubbed mock method returns set value [OK]
- Forgetting to initialize mocks before use
- Expecting real method output instead of stubbed
- Confusing null return with stubbed return
@Mock:import org.junit.jupiter.api.Test;
import org.mockito.Mock;
class UserServiceTest {
@Mock
UserRepository repo;
@Test
void testFindUser() {
when(repo.findUserById(1)).thenReturn(new User(1, "Alice"));
UserService service = new UserService(repo);
User user = service.findUser(1);
assertEquals("Alice", user.getName());
}
}Solution
Step 1: Check mock initialization
The code declares@Mock UserRepository repo;but never initializes mocks withMockitoAnnotations.openMocks(this)or similar.Step 2: Understand consequence of missing initialization
Without initialization,repois null, so callingwhen(repo.findUserById(1))causes a NullPointerException.Final Answer:
Mocks are not initialized before use -> Option CQuick Check:
Always initialize mocks before using them [OK]
- Forgetting MockitoAnnotations.openMocks(this)
- Assuming @Mock auto-initializes mocks
- Misusing when() without initialized mocks
@Mock to create fake objects for both. Which of the following is the best practice to ensure your mocks work correctly in the test?Solution
Step 1: Understand mock initialization best practice
Mocks annotated with@Mockmust be initialized before use, typically by callingMockitoAnnotations.openMocks(this)in a setup method.Step 2: Evaluate other options
Manually creating mocks withnewis incorrect; real instances break isolation; local variables lose scope and initialization benefits.Final Answer:
Initialize mocks withMockitoAnnotations.openMocks(this)in a setup method -> Option BQuick Check:
Initialize mocks in setup for reliable tests [OK]
- Creating mocks manually with new keyword
- Using real objects instead of mocks
- Declaring mocks inside test methods without initialization
Ready to prove it?
Pass the test and this pattern moves unknown
