Introduction

Mockito is one of the most widely used Java frameworks for unit testing, allowing developers to mock dependencies effectively. In this guide, we will explore the fundamentals of Mockito, demonstrating how to create mock objects, stub methods, and verify interactions.


Why Use Mockito?

Unit tests should be isolated and independent, which often requires simulating dependencies instead of using actual implementations. Mockito provides:

  • Simplified test setup: Easily create mock objects.
  • Behavior verification: Ensure expected interactions occur.
  • Flexible stubbing: Control method responses dynamically.
  • Improved test performance: Avoid costly resource usage in tests.

Setting Up Mockito

To use Mockito, add the following dependencies to your pom.xml (for Maven):

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-core</artifactId>
    <version>4.0.0</version>
    <scope>test</scope>
</dependency>

For Gradle, add:

testImplementation 'org.mockito:mockito-core:4.0.0'

Creating Mock Objects

Mockito allows you to create mock objects easily using the mock() method:

import org.junit.jupiter.api.Test;
import static org.mockito.Mockito.*;

class SampleServiceTest {
    @Test
    void testMocking() {
        MyService mockService = mock(MyService.class);
        when(mockService.getData()).thenReturn("Mocked Data");
        System.out.println(mockService.getData()); // Outputs: Mocked Data
    }
}

Stubbing Methods

Stubbing allows controlling method return values:

when(mockService.getData()).thenReturn("Test Data");

You can also throw exceptions for negative scenarios:

when(mockService.getData()).thenThrow(new RuntimeException("Error"));

Verifying Interactions

Mockito enables interaction verification:

verify(mockService).getData();
verify(mockService, times(1)).getData();

You can also check method call sequences:

InOrder inOrder = inOrder(mockService);
inOrder.verify(mockService).getData();
inOrder.verify(mockService).processData();

Using @Mock and @InjectMocks

Mockito annotations simplify test setup:

@ExtendWith(MockitoExtension.class)
class SampleServiceTest {
    @Mock
    MyService mockService;
    
    @InjectMocks
    SampleService sampleService;
}

Advanced Mockito Features

Argument Matchers:

when(mockService.getData(anyString())).thenReturn("Response");

Spying on Real Objects:

MyService spyService = spy(new MyService());

Mocking Static Methods (Mockito 3.4+):

try (MockedStatic<MyClass> mocked = mockStatic(MyClass.class)) {}

Best Practices

  1. Keep tests independent and focused.
  2. Use @Mock annotations instead of manual mocking.
  3. Verify only essential interactions.
  4. Avoid unnecessary stubbing.
  5. Use spy() cautiously.

External Resources


Conclusion

Mockito simplifies dependency mocking in Java unit tests, improving test accuracy and reliability. By leveraging its features effectively, developers can ensure robust and maintainable test suites.


FAQs

1. What is Mockito?

Mockito is a Java framework used for mocking dependencies in unit tests.

2. Why should I use Mockito?

It isolates dependencies, making unit tests faster, more reliable, and easier to write.

3. How do I create a mock object?

Use mock(ClassName.class) to create a mock instance.

4. What is the difference between mock() and spy()?

mock() creates a complete mock, while spy() wraps a real object, allowing partial mocking.

5. How do I verify interactions with a mock?

Use verify(mockObject).methodName(); to check method calls.

6. Can Mockito mock static methods?

Yes, from Mockito 3.4 onwards, you can mock static methods using mockStatic().

7. How do I mock a method to return different values?

Use when().thenReturn() or thenAnswer() for dynamic responses.

8. What is @InjectMocks used for?

It automatically injects mocked dependencies into the tested class.

9. Can Mockito mock final classes?

Yes, by enabling the mock-maker-inline feature.

10. Is Mockito free to use?

Yes, Mockito is an open-source framework under the MIT license.