Olson CloudWorks 🚀

How to use Mockito with JUnit 5

September 19, 2026

How to use Mockito with JUnit 5

Testing is a cornerstone of robust software development, and when it comes to Java, JUnit has long been the go-to framework. But to truly isolate and test individual components, we often need mocking capabilities. That’s where Mockito comes in. This article will guide you through the process of learning how to use Mockito with JUnit 5, the latest version of the popular testing framework. We will cover everything from setting up your project to writing effective unit tests that leverage Mockito’s powerful features. By combining JUnit 5’s modern features with Mockito’s intuitive mocking API, you can create comprehensive and reliable test suites, ensuring your code behaves as expected and minimizing the risk of bugs. This combination allows developers to write cleaner, more maintainable tests that focus on specific units of code, leading to better overall software quality. We will explore how to create mocks, define their behavior, and verify interactions, providing you with a solid foundation for effective unit testing.

Setting Up Your Project for Mockito and JUnit 5

Before you can start writing tests with Mockito and JUnit 5, you need to set up your project correctly. This involves adding the necessary dependencies to your project’s build file, typically using Maven or Gradle. For Maven, you’ll need to add the JUnit 5 and Mockito dependencies. Make sure to use the latest versions of both libraries to take advantage of the newest features and bug fixes. For example, you might use JUnit Jupiter (JUnit 5) version 5.8.2 and Mockito core version 4.0.0.

To add these dependencies using Maven, include the following in your pom.xml file:

<dependencies> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>5.8.2</version> <scope>test</scope> </dependency> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <version>4.0.0</version> <scope>test</scope> </dependency> </dependencies> 

For Gradle, you’ll add these dependencies to your build.gradle file:

dependencies { testImplementation 'org.junit.jupiter:junit-jupiter-api:5.8.2' testImplementation 'org.mockito:mockito-core:4.0.0' } 

Once you’ve added the dependencies, make sure to refresh your project in your IDE so that the libraries are available for use. With the dependencies in place, you are now ready to start writing unit tests using JUnit 5 and Mockito. You can find more information on setting up JUnit 5 at the official JUnit 5 website JUnit 5 Documentation.

Creating Your First Mock with Mockito

Mockito simplifies the process of creating mock objects, which are essential for isolating the unit under test. A mock object is a simulated object that mimics the behavior of a real object, allowing you to control its responses and verify interactions. Mockito provides several ways to create mocks, including using the @Mock annotation and the Mockito.mock() method.

The @Mock annotation is part of Mockito’s JUnit integration and requires you to initialize the mocks using MockitoAnnotations.openMocks(this) in your test class or using the @ExtendWith(MockitoExtension.class) annotation. The Mockito.mock() method allows you to create mocks programmatically without any special setup. For example, if you have a class called MyService, you can create a mock of it using MyService myServiceMock = Mockito.mock(MyService.class);. This mock object can then be used in your tests to simulate the behavior of the real MyService.

Once you have created a mock object, you can define its behavior using Mockito’s when() and thenReturn() methods. For instance, if you want the myServiceMock.getData() method to return a specific value, you can use when(myServiceMock.getData()).thenReturn("mocked data");. This allows you to control the responses of your dependencies and test the behavior of your code under different conditions. This granular control is key to effective unit testing, ensuring that each component is thoroughly tested in isolation.

Here’s an example showcasing the use of @Mock and when():

import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.when; @ExtendWith(MockitoExtension.class) class MyTest { @Mock private MyService myService; @Test void testGetData() { when(myService.getData()).thenReturn("mocked data"); assertEquals("mocked data", myService.getData()); } } 

Verifying Interactions with Mockito

One of the most powerful features of Mockito is its ability to verify interactions with mock objects. This allows you to ensure that your code is calling the correct methods on its dependencies with the expected arguments. Mockito provides the verify() method for this purpose, which allows you to check that a specific method was called on a mock object. You can also specify the number of times the method should have been called using methods like times(), atLeast(), and atMost().

For example, if you want to verify that the myServiceMock.processData("input") method was called exactly once, you can use verify(myServiceMock, times(1)).processData("input");. If you want to verify that it was called at least twice, you can use verify(myServiceMock, atLeast(2)).processData("input");. These methods allow you to precisely control your verification logic and ensure that your code is interacting with its dependencies as expected.

Mockito also provides the ArgumentCaptor class, which allows you to capture the arguments passed to a method call. This is particularly useful when you need to verify that a method was called with specific arguments, but you don’t know the exact values at compile time. By capturing the arguments, you can then assert that they meet certain criteria. According to Martin Fowler, “Mocks aren’t stubs” Mocks Aren’t Stubs, emphasizing the importance of verifying behavior over just providing canned responses.

Consider this example:

import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.mockito.Mockito.verify; @ExtendWith(MockitoExtension.class) class MyTest { @Mock private MyService myService; @Test void testProcessData() { MyClass myClass = new MyClass(myService); myClass.doSomething("input"); ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class); verify(myService).processData(argumentCaptor.capture()); assertEquals("input", argumentCaptor.getValue()); } } class MyClass { private final MyService myService; public MyClass(MyService myService) { this.myService = myService; } public void doSomething(String data) { myService.processData(data); } } 

In this example, we capture the argument passed to the processData method and then assert that it is equal to “input.” This allows us to verify that the doSomething method is correctly passing the data to the processData method.

Featured Snippet: Mockito’s verification capabilities are crucial for ensuring that interactions with dependencies occur as expected. By using verify(), times(), atLeast(), and ArgumentCaptor, developers can write comprehensive tests that validate the behavior of their code and prevent integration issues. Proper verification ensures that the unit under test is correctly utilizing its dependencies, contributing to overall system reliability and maintainability.

Advanced Mockito Features with JUnit 5

Mockito offers several advanced features that can further enhance your unit testing capabilities. These include features like mocking static methods, mocking constructors, and using custom argument matchers. Mocking static methods can be challenging, but Mockito provides the mockStatic() method to enable this functionality. This allows you to control the behavior of static methods and test code that relies on them.

Mocking constructors allows you to replace the creation of new objects with mock objects, which can be useful when you want to isolate the unit under test from the dependencies of the objects it creates. Mockito provides the mockConstruction() method for this purpose. Custom argument matchers allow you to define your own criteria for matching arguments passed to method calls. This can be useful when you need to match arguments based on complex logic or when you want to ignore certain parts of the argument.

Mockito also integrates well with JUnit 5’s parameterized tests, allowing you to run the same test with different inputs. This can be useful for testing different scenarios and ensuring that your code behaves correctly under a variety of conditions. Parameterized tests can be defined using the @ParameterizedTest annotation in JUnit 5. For more advanced usage and examples, refer to the official Mockito documentation Mockito Official Website.

Here are some key points to remember:

  • Use @ExtendWith(MockitoExtension.class) to enable Mockito annotations in JUnit 5.
  • Use when().thenReturn() to define the behavior of mock objects.
  • Use verify() to verify interactions with mock objects.

Here’s an example showcasing static method mocking:

import org.junit.jupiter.api.Test; import org.mockito.MockedStatic; import org.mockito.Mockito; import static org.junit.jupiter.api.Assertions.assertEquals; class MyTest { @Test void testStaticMethod() { try (MockedStatic<MyStaticClass> mockedStatic = Mockito.mockStatic(MyStaticClass.class)) { mockedStatic.when(MyStaticClass::staticMethod).thenReturn("mocked static"); assertEquals("mocked static", MyStaticClass.staticMethod()); } } } class MyStaticClass { public static String staticMethod() { return "real static"; } } 

FAQ

What is Mockito?
Mockito is a popular Java mocking framework used for unit testing. It allows you to create mock objects that simulate the behavior of real objects, enabling you to isolate and test individual components of your code.
Why use Mockito with JUnit 5?
Mockito and JUnit 5 together provide a powerful combination for writing comprehensive and reliable unit tests. JUnit 5 provides a modern testing framework, while Mockito simplifies the process of creating and managing mock objects. This combination allows developers to write cleaner, more maintainable tests that focus on specific units of code.
How do I add Mockito to my JUnit 5 project?
You can add Mockito to your JUnit 5 project by adding the necessary dependencies to your project's build file (e.g., `pom.xml` for Maven or `build.gradle` for Gradle). Make sure to include both JUnit 5 and Mockito dependencies.
What is the difference between `@Mock` and `Mockito.mock()`?
`@Mock` is an **Question & Answer :** How can I use injection with Mockito and JUnit 5?

In JUnit 4, I can just use the @RunWith(MockitoJUnitRunner.class) annotation.
In JUnit 5, there is no @RunWith Annotation.

There are different ways to use Mockito - I’ll go through them one by one.

Manually

Creating mocks manually with Mockito::mock works regardless of the JUnit version (or test framework for that matter).

Annotation Based

Using the @Mock-annotation and the corresponding call to MockitoAnnotations::initMocks to create mocks works regardless of the JUnit version (or test framework for that matter but Java 9 could interfere here, depending on whether the test code ends up in a module or not).

Mockito Extension

JUnit 5 has a powerful extension model and Mockito recently published one under the group / artifact ID org.mockito : mockito-junit-jupiter.

You can apply the extension by adding @ExtendWith(MockitoExtension.class) to the test class and annotating mocked fields with @Mock. From MockitoExtension’s JavaDoc:

@ExtendWith(MockitoExtension.class) public class ExampleTest { @Mock private List list; @Test public void shouldDoSomething() { list.add(100); } } 

The MockitoExtension documentation describes other ways to instantiate mocks, for example with constructor injection (if you rpefer final fields in test classes).

No Rules, No Runners

JUnit 4 rules and runners don’t work in JUnit 5, so the MockitoRule and the Mockito runner can not be used.