Mockito
Mock Objects
Unit Testing
Java
Test Automation

Initialising mock objects - Mockito

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Overview of Mockito

Mockito is a powerful Java library used for creating mock objects in unit testing. Mock objects allow developers to simulate the behavior of real objects in a controlled way, ensuring tests focus only on the code being tested, without relying on external dependencies. Mockito delivers a clean API and expressive syntax, which can greatly enhance test readability and maintainability.

Why Use Mocking?

Mocking is essential in unit testing, particularly when:

  • The actual object involves significant setup complexity.
  • The real object interacts with an external system like a database or network.
  • Dependencies may have unpredictable behavior or are difficult to trigger into every possible state.
  • Tests need to verify the interaction between objects.

Initializing Mock Objects with Mockito

In Mockito, you can create mock objects using the Mockito.mock() static method. Initialization can be straightforward or further customized to meet specific testing needs.

Basic Initialization

To mock a class or an interface, you simply call:

java
1import static org.mockito.Mockito.mock;
2
3// Creating a mock object of a Class
4MyService myServiceMock = mock(MyService.class);
5
6// Creating a mock object of an Interface
7MyInterface myInterfaceMock = mock(MyInterface.class);

Using Annotations

Mockito provides annotations to streamline the mock initialization process, notably @Mock and @InjectMocks.

  • @Mock: Marks a field for mocking.
  • @InjectMocks: Injects mock fields into the tested object.

To use these annotations, annotate your class with @RunWith(MockitoJUnitRunner.class) or call MockitoAnnotations.initMocks(this) in a @Before method.

java
1import org.junit.Before;
2import org.junit.Test;
3import org.junit.runner.RunWith;
4import org.mockito.InjectMocks;
5import org.mockito.Mock;
6import org.mockito.MockitoAnnotations;
7import org.mockito.junit.MockitoJUnitRunner;
8
9// Using MockitoJUnitRunner
10@RunWith(MockitoJUnitRunner.class)
11public class MyServiceTest {
12
13    @Mock
14    private DependencyService dependencyServiceMock;
15
16    @InjectMocks
17    private MyService myService;
18
19    @Test
20    public void testServiceMethod() {
21        // Write the test logic
22    }
23}
24
25// Using MockitoAnnotations
26public class MyServiceTest {
27
28    @Mock
29    private DependencyService dependencyServiceMock;
30
31    @InjectMocks
32    private MyService myService;
33
34    @Before
35    public void setUp() {
36        MockitoAnnotations.initMocks(this); // Initialize mocks
37    }
38
39    @Test
40    public void testServiceMethod() {
41        // Write the test logic
42    }
43}

Stubbing Method Calls

Stubbing allows you to define the behavior of a mock object when certain methods are called.

java
1import static org.mockito.Mockito.when;
2import static org.mockito.Mockito.verify;
3
4@Test
5public void testMethod() {
6    // Stubbing
7    when(dependencyServiceMock.getData()).thenReturn(mockData);
8
9    // Use the mock in the test
10    MyData result = myService.processData();
11
12    // Verification
13    verify(dependencyServiceMock).getData();
14    assertEquals(expectedData, result);
15}

Using Argument Matchers

Mockito provides matchers for complex argument matching using the ArgumentMatchers class.

java
1import static org.mockito.Mockito.any;
2import static org.mockito.Mockito.eq;
3
4@Test
5public void testArgumentMatchers() {
6    when(dependencyServiceMock.calculate(any(), eq("constant"))).thenReturn(expectedValue);
7    
8    result = myService.calculateSomething(dynamicValue, "constant");
9
10    assertEquals(expectedValue, result);
11}

Spy Objects

A spy is a partial mock that wraps around an actual object, allowing you to call real methods while ensuring some methods can be stubbed.

java
1import static org.mockito.Mockito.spy;
2import static org.mockito.Mockito.doReturn;
3
4@Test
5public void testSpy() {
6    List<String> listSpy = spy(new ArrayList<>());
7
8    // Stubbing size method 
9    doReturn(5).when(listSpy).size();
10    
11    // Using real methods
12    listSpy.add("Test");
13    
14    assertEquals(5, listSpy.size());
15}

Key Points Summary

FeatureDescription
Basic InitializationUse Mockito.mock() for creating mock objects.
Annotation-BasedUse @Mock and @InjectMocks for cleaner tests.
StubbingDefine mock behavior for specific method calls.
Argument MatchersUse matchers for flexible argument stubbing.
Spy ObjectsPartial mocks that wrap around real objects.
VerificationVerify interaction and method calls on mocks.

Conclusion

Mockito simplifies the process of mocking in Java tests, making it possible to create reliable and maintainable unit tests more efficiently. By using mocking frameworks like Mockito, developers can isolate parts of their code, specifically test interactions, and improve software robustness. Understanding and using Mock, Spy, and the many utilities provided by Mockito effectively is a crucial skill in modern Java development.


Course illustration
Course illustration

All Rights Reserved.