Mockito is a popular mocking framework for Java that allows you to create and use mock objects in your tests. Mock objects help you isolate the code under test by simulating the behavior of dependencies. Here's a basic guide on how to use Mockito in Java:
Add Mockito to Your Project:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.11.2</version> <!-- Use the latest version available -->
<scope>test</scope>
</dependency>
Create Mock Objects:
Mockito.mock()
to create a mock object for a specific class or interface.import static org.mockito.Mockito.*;
// Create a mock object for an interface
MyInterface myMock = mock(MyInterface.class);
// Create a mock object for a class
MyClass myClassMock = mock(MyClass.class);
Define Mock Behavior:
when().thenReturn()
to define the behavior of your mock object when specific methods are called.// Example for an interface
when(myMock.someMethod()).thenReturn(someValue);
// Example for a class
when(myClassMock.someMethod()).thenReturn(someValue);
Verify Interactions:
verify()
to check that specific methods were called on your mock object.// Verify that a method was called with specific arguments
verify(myMock).someMethod(arg1, arg2);
Argument Matchers:
// Example using any() matcher
when(myMock.someMethod(any(String.class))).thenReturn(someValue);
Annotations (Optional):
@Mock
and @InjectMocks
to simplify the process of creating and injecting mocks.@Mock
private MyInterface myMock;
@InjectMocks
private MyClass myClassUnderTest;