What if you could skip building fake parts and test your code instantly?
Why @Mock annotation in JUnit? - Purpose & Use Cases
Imagine testing a class that depends on a database or a web service. Manually creating fake versions of these dependencies by writing extra code is like trying to build a toy car from scratch every time you want to play.
Manually writing fake objects is slow and error-prone. It takes a lot of time to create and maintain these fakes, and mistakes can cause tests to fail for the wrong reasons, making debugging frustrating.
The @Mock annotation automatically creates simple fake versions of dependencies. This lets you focus on testing your class without worrying about the complex setup, making tests faster and easier to write.
FakeDatabase db = new FakeDatabase(); MyService service = new MyService(db);
@Mock Database db; @InjectMocks MyService service;
With @Mock, you can quickly isolate and test parts of your code without building complicated setups, speeding up development and improving test reliability.
When testing a payment processor, you don't want to call the real payment gateway every time. Using @Mock lets you fake the gateway responses easily, so tests run fast and safely.
Manual fakes are slow and fragile.
@Mock creates fake dependencies automatically.
This makes tests simpler, faster, and more reliable.
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
