Mockito testing framework uses

Introduction to Mockito

Mockito is a popular Java testing framework for mocking objects, creating test cases, and unit testing. It provides a set of simple and powerful APIs for creating and manipulating mock objects (Mocks), and verifying the behavior of mock objects. Here are the basic steps for unit testing with Mockito:

1. Import dependencies: First, add Mockito dependencies in the project's build file (such as pom.xml).

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

2. Create mock objects (Mocks): Use the Mockito.mock() method to create a mock object that will replace the actual dependent object.

// 创建一个模拟对象
MyDependency myDependency = Mockito.mock(MyDependency.class);

3. Set the behavior of the mock object: use the Mockito.when() method to set the behavior of the mock object, and specify the return value when the method is called.

// 设置模拟对象的行为
Mockito.when(myDependency.someMethod()).thenReturn("Mocked value");

4. Execute the test code: call the method under test, and use the mock object instead of the actual dependent object.

// 执行测试代码
MyClass myClass = new MyClass(myDependency);
String result = myClass.myMethod();

5. Verify the behavior of the mock object: Use the Mockito.verify() method to verify that the method of the mock object is called as expected.

// 验证模拟对象的行为
Mockito.verify(myDependency).someMethod();

This is just a basic usage example of Mockito, there are many other features and usages to explore. Mockito provides many other APIs for more complex testing scenarios, such as parameter matching, successive calls to mocked objects, etc. You can refer to the official documentation of Mockito for more detailed usage and examples: https://site.mockito.org/

Guess you like

Origin blog.csdn.net/m0_44980168/article/details/131568588