📜  mockito (1)

📅  最后修改于: 2023-12-03 15:32:55.189000             🧑  作者: Mango

Mockito

Mockito is an open source testing framework for Java that allows you to easily create mock objects for your unit tests. It can be used to stub out dependencies that your code relies on, allowing you to test your code in isolation.

Features

Mockito provides a wide range of features that simplifies the process of creating mock objects and verifying their behavior. Some of the key features include:

  • Easy mocking of objects and interfaces
  • Verification of method calls
  • Support for argument matching and capturing
  • Stubbing of method calls
  • Configurable behavior of mock objects
Getting Started

To get started with Mockito, you first need to add the Mockito dependency to your project. You can do this by adding the following code to your pom.xml file:

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

Once you have added the dependency, you can start using Mockito in your tests. Here is an example of how to create a mock object:

// create a mock object for the List interface
List<String> mockedList = Mockito.mock(List.class);

You can then configure the behavior of the mock object to return specific values or throw exceptions using the when() method:

// configure the mock object to return "hello" when the get(0) method is called
Mockito.when(mockedList.get(0)).thenReturn("hello");

You can also verify the behavior of the mock object using the verify() method:

// verify that the get(0) method was called on the mock object with the argument "hello"
Mockito.verify(mockedList).get(0);
Conclusion

Mockito is a powerful testing framework that simplifies the process of creating mock objects and verifying their behavior. By using Mockito in your tests, you can write more effective tests that are easier to maintain and refactor.