Mock objects help us test parts of a program by pretending to be other parts. This way, we can check if our code works without needing everything ready.
Mock objects in JUnit
import static org.mockito.Mockito.*; // Create a mock object MyClass mockObject = mock(MyClass.class); // Define behavior when(mockObject.someMethod()).thenReturn(someValue); // Use mock in test assertEquals(someValue, mockObject.someMethod());
Use mock() to create a fake version of a class.
Use when(...).thenReturn(...) to tell the mock what to return when a method is called.
size() is called.MyList mockList = mock(MyList.class); when(mockList.size()).thenReturn(5); assertEquals(5, mockList.size());
getData() is called.MyService mockService = mock(MyService.class); when(mockService.getData()).thenReturn("Hello"); assertEquals("Hello", mockService.getData());
This test creates a mock UserRepository that returns "Alice" for ID 1. Then it checks if UserService returns the same name. This way, we test UserService without needing a real database.
import static org.mockito.Mockito.*; import static org.junit.jupiter.api.Assertions.*; import org.junit.jupiter.api.Test; class UserService { private UserRepository repo; public UserService(UserRepository repo) { this.repo = repo; } public String getUserName(int id) { return repo.findNameById(id); } } interface UserRepository { String findNameById(int id); } public class UserServiceTest { @Test void testGetUserName() { UserRepository mockRepo = mock(UserRepository.class); when(mockRepo.findNameById(1)).thenReturn("Alice"); UserService service = new UserService(mockRepo); String name = service.getUserName(1); assertEquals("Alice", name); } }
Mocks help isolate the code you want to test from other parts.
Always define what the mock should return to avoid unexpected results.
Mockito is a popular library for creating mocks in JUnit tests.
Mock objects pretend to be real objects for testing.
They help test code in isolation and control responses.
Use mock() and when(...).thenReturn(...) to create and control mocks.
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
