The @Mock annotation helps create fake objects that imitate real ones. This lets you test parts of your code without using the real objects, making tests faster and simpler.
@Mock annotation in JUnit
@Mock private ClassName mockObject;
Use @Mock on a field to create a mock object of that type.
Remember to initialize mocks with MockitoAnnotations.openMocks(this); in your setup method.
@Mock private List<String> mockedList;
UserService class.@Mock private UserService userServiceMock;
This test creates a mock List using @Mock. It sets the size to return 3 when called. The test checks that the size method returns 3 and verifies that the size method was called.
import static org.mockito.Mockito.*; import org.junit.jupiter.api.*; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.List; public class MockAnnotationTest { @Mock private List<String> mockedList; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); } @Test void testMockedList() { when(mockedList.size()).thenReturn(3); Assertions.assertEquals(3, mockedList.size()); verify(mockedList).size(); } }
Always initialize mocks before using them to avoid null pointers.
Mocks do not execute real code; they only simulate behavior you define.
Use verify() to check if mocked methods were called as expected.
@Mock creates fake objects for testing.
It helps isolate the code under test from real dependencies.
Remember to initialize mocks and define their behavior before testing.
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
