Mockito Quick Intro

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:

  • If you're using a build tool like Maven or Gradle, you can include Mockito as a dependency.
    • For Maven:
<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:

  • Use 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:

  • Use 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:

  • Use 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:

  • Use Mockito's argument matchers to specify flexible argument matching.
// Example using any() matcher
when(myMock.someMethod(any(String.class))).thenReturn(someValue);

Annotations (Optional):

  • You can use annotations like @Mock and @InjectMocks to simplify the process of creating and injecting mocks.
@Mock
private MyInterface myMock;

@InjectMocks
private MyClass myClassUnderTest;