Why mocking isolates units under test in JUnit - Automation Benefits in Action
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; // External service interface interface Service { int getValue(); } // Class under test class Calculator { private final Service service; public Calculator(Service service) { this.service = service; } public int calculate() { // Uses service to get a value and adds 10 return service.getValue() + 10; } } @ExtendWith(MockitoExtension.class) public class CalculatorTest { @Mock Service serviceMock; @InjectMocks Calculator calculator; @Test void testCalculateWithMockedService() { // Arrange: define mock behavior when(serviceMock.getValue()).thenReturn(5); // Act: call method under test int result = calculator.calculate(); // Assert: verify result is as expected assertEquals(15, result, "Calculator should add 10 to mocked service value"); // Verify: service method was called once verify(serviceMock, times(1)).getValue(); } }
This test uses Mockito to create a mock of the Service interface. The Calculator depends on this service.
By mocking Service, we control its behavior to return 5 when getValue() is called.
This isolates the Calculator from the real Service implementation, so the test only verifies Calculator's logic.
The @Mock annotation creates the mock, and @InjectMocks injects it into the Calculator instance.
The test asserts that the result is 15 (5 from mock + 10), and verifies the mock method was called exactly once.
This shows how mocking isolates the unit under test by replacing dependencies with controlled mocks.
Now add data-driven testing with 3 different mock return values and expected results
Practice
Mocking helps to:Solution
Step 1: Understand the purpose of mocking
Mocking replaces real dependencies with fake ones to isolate the code being tested.Step 2: Identify the effect on tests
This isolation makes tests faster and more reliable by controlling external factors.Final Answer:
Isolate the unit under test by replacing its dependencies with fake objects -> Option BQuick Check:
Mocking isolates code = D [OK]
- Thinking mocking slows tests down
- Believing mocking generates test data automatically
- Confusing mocking with replacing the whole app
Solution
Step 1: Recall Mockito syntax for mocking
Mockito uses the static methodmock()with the class type as argument.Step 2: Check each option
Only MyClass mock = Mockito.mock(MyClass.class); uses the correct syntax:Mockito.mock(MyClass.class);Final Answer:
MyClass mock = Mockito.mock(MyClass.class); -> Option DQuick Check:
Mockito.mock(Class) syntax = A [OK]
- Using new keyword instead of Mockito.mock
- Wrong method names like create()
- Incorrect class references without .class
class ServiceTest {
@Mock
Repository repo;
@InjectMocks
Service service;
@Test
void testGetData() {
when(repo.getData()).thenReturn("mocked data");
String result = service.getData();
assertEquals("mocked data", result);
}
}What is the main reason this test passes even if the real
Repository is not connected to a database?Solution
Step 1: Understand the role of @Mock and when()
Therepois mocked to return "mocked data" whengetData()is called.Step 2: Analyze test behavior
The test passes because the mock returns the expected string, independent of any real database connection.Final Answer:
Becauserepois a mock that returns controlled data -> Option AQuick Check:
Mock returns controlled data = C [OK]
- Assuming real database is used
- Thinking service ignores repository
- Believing test lacks assertions
@Test
void testCalculate() {
Calculator calc = Mockito.mock(Calculator.class);
when(calc.add(2, 3)).thenReturn(5);
int result = calc.add(2, 3);
assertEquals(6, result);
}Solution
Step 1: Review mock setup and behavior
The mock is set to return 5 whenadd(2, 3)is called.Step 2: Check assertion correctness
The assertion expects 6, but the mock returns 5, causing failure.Final Answer:
The expected value in assertEquals is incorrect -> Option AQuick Check:
Assert expected matches mock return = B [OK]
- Expecting wrong values in assertions
- Confusing mock creation syntax
- Missing @Mock annotation on mock fields
Consider a service that calls a database and a web API. Which benefit does mocking these dependencies provide?
Solution
Step 1: Understand dependency isolation
Mocking replaces real dependencies like database and API with controlled fake versions.Step 2: Identify benefits for testing
This isolation allows testing service logic reliably without depending on external systems' availability or state.Final Answer:
It allows testing the service logic without relying on database or API availability -> Option CQuick Check:
Mocking isolates external dependencies = A [OK]
- Thinking mocking slows code
- Believing mocking fixes bugs automatically
- Confusing mocking with skipping tests
Ready to prove it?
Pass the test and this pattern moves unknown
