Mocking dependencies for Java testing with Mockito.
Jul 08, 2025 am 02:25 AMMockito is a commonly used mocking framework in Java unit testing, used to simulate dependency behavior to avoid side effects caused by real calls. 1. Mock is to create a "fake" object instead of real dependencies, which facilitates control of return values, verify calls, and avoid external influences; 2. Use Mockito to create Mock objects through annotations or manually; 3. The core functions include when(...).thenReturn(...) to define behavior and verify(...) to verify calls; 4. Precautions include avoiding excessive mock, requiring additional tools to handle static methods, ensuring correct initialization, and verifying the number of calls. Mastering these core content can effectively improve testing efficiency and reliability.
In Java unit testing, Mockito is one of the most commonly used mocking frameworks. It can help you simulate the behavior of dependent objects and avoid side effects caused by real calls, such as database access, network requests, etc. This way you can focus on the logic testing of the current class.

What is a Mock? Why Mock dependencies?
Mock is to create a "fake" object to replace real dependencies.
For example: You are testing a UserService
which relies on a UserRepository
. If you don't use mock, you may really check the database every time you test, which is inefficient and prone to errors.

The advantage of using Mockito is that you can:
- Control the data returned by dependencies
- Verify that a method has been called
- Avoid external systems affecting test results
How to create a Mock object using Mockito?
Using Mockito is simple, add dependencies (such as Gradle):

testImplementation 'org.mockito:mockito-core:5.0.0'
Then you can use annotations or manually create mocks in your tests:
@Mock private UserRepository userRepository; @BeforeEach void setUp() { MockitoAnnotations.openMocks(this); }
Or write directly:
UserRepository userRepository = Mockito.mock(UserRepository.class);
Both methods are OK, depending on which one you are used to.
How to define Mock behavior and verification calls?
This is the most core feature of Mockito. Common methods are:
-
when(...).thenReturn(...)
: Define what a method call returns -
verify(...)
: Verify whether a method has been called
For example:
when(userRepository.findById(1L)).thenReturn(Optional.of(new User("Alice"))); User user = userService.getUserById(1L); assertEquals("Alice", user.getName()); verify(userRepository).findById(1L);
The above code means:
- When
userRepository.findById(1L)
is called, an Optional containing Alice is returned - Then call
userService.getUserById()
method - Finally, verify whether this method really calls
findById
This approach is great for testing business logic without relying on real data sources.
Frequently Asked Questions and Notes
- Don't overmock : If a class does not have complex external dependencies, there is no need to force mocking.
- Note static methods and constructors : Mockito does not support mock static methods by default, and it needs to be used with PowerMock or using a newer version of Mockito Inline.
- Don't forget to initialize mocks : be sure to call
MockitoAnnotations.openMocks(this);
before using@Mock
annotation, otherwise the pointer will be thrown. - Number of verification times : You can use
verify(x, times(2))
to confirm that the method has been called several times, or you can useatLeastOnce()
and other more flexible methods.
Basically that's all. Mockito is quick to use and powerful, and is an indispensable tool in Java unit testing. As long as you master a few core APIs, you can write clear and reliable test code.
The above is the detailed content of Mocking dependencies for Java testing with Mockito.. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

With the popularity of the Internet, Java back-end development has become an important field. In the development process, unit testing is a very critical step, and Mockito is an excellent API unit test simulation tool. This article will introduce how to use Mockito in Java back-end development. What is Mockito? Mockito is a Java framework that provides API unit testing simulation capabilities in the form of Mock objects. Mock objects refer to some virtual objects whose behavior is set by us

Mockito framework annotations simplify the stub generation and verification process: @Mock: automatically generate and manage mock objects. @Captor: Capture the parameter value passed to the mock method. @InjectMocks: Automatically inject mock objects into the class under test. @Spy: Create some stub objects and retain the original method implementation.

Introduction RESTful APIs are becoming increasingly popular, so ensuring their robustness becomes critical. Unit testing is an effective way to verify the functionality and behavior of your code, especially for RESTful APIs. This article explains how to use JAX-RS and unit testing frameworks such as Mockito and RESTAssured to test RESTful code. Introduction to JAX-RS JAX-RS is a Java API for building RESTful APIs. It provides a set of annotations and classes for defining resources and handling HTTP requests and responses. Using JAX-RS, developers can easily create RESTful services that can communicate with a variety of clients. unit test

Introduction to Mockito When calling the method of a mock object, the real method will not be executed, but the default value of the return type, such as object returns null, int returns 0, etc. Otherwise, the method is specified by specifying when(method).thenReturn(value) return value. At the same time, the mock object can be tracked and the verify method can be used to see whether it has been called. The spy object will execute the real method by default, and the return value can be overridden through when.thenReturn. It can be seen that as long as mock avoids executing some methods and directly returns the specified value, it is convenient for other tests. Service test cases require dependencies junitjunit4.1

Mockito and JUnit join forces to improve unit testing efficiency: Mockito allows the creation of test stubs and mock objects to verify the expected interactions of the code. JUnit provides a framework to make test writing and running easier. When used together, you can create highly readable and maintainable tests that effectively verify the correctness of your code.

How to conduct testing and quality assurance of Java development projects In comprehensive software development projects, testing and quality assurance are important links to ensure the stability, reliability and effectiveness of the final software product. For Java development projects, comprehensive testing and quality assurance are also required to ensure the successful implementation of the project. This article will discuss how to conduct testing and quality assurance of Java development projects. Define a test plan Before conducting testing, you first need to develop a test plan. The test plan should include the scope of the test, the purpose and objectives of the test, the environment of the test

Steps to test Java functions using Mockito: Add Mockito dependencies. Create mock objects and set mock behavior. Call the function to be tested. Assert the expected behavior of a function. Use verify() to verify simulated interactions.

Simple and easy-to-understand method of writing Java test classes: Make your code more reliable Introduction: In the software development process, writing test code is a very important link. By testing the code, we can verify whether our code can run normally, and can quickly locate and fix problems in subsequent development. This article will introduce a simple and easy-to-understand method of writing Java test classes to help readers better conduct code testing. What is test code? Test code is a piece of code used to verify the function of the program. Its purpose is to determine whether the code is as expected.
