🎯Mockito

Introduction

Mockito is an open-source Java testing framework that allows developers to create mock objects of classes and interfaces to test the behavior of other objects in the system. It is widely used to mock dependencies in unit tests, allowing developers to test individual units of code in isolation.

Basic Syntax

  1. Creating a mock object:

MyClass myMock = Mockito.mock(MyClass.class);
  1. Setting expectations on mock objects:

Mockito.when(myMock.someMethod()).thenReturn(someValue);
  1. Verifying the behavior of mock objects:

Mockito.verify(myMock, times(1)).someMethod();

Mocking Methods

  1. Returning a specific value:

Mockito.when(myMock.someMethod()).thenReturn(someValue);
  1. Throwing an exception:

Mockito.when(myMock.someMethod()).thenThrow(new Exception());
  1. Calling the real method:

Mockito.when(myMock.someMethod()).thenCallRealMethod();

Verifying Behavior

  1. Verifying that a method was called:

Mockito.verify(myMock, times(1)).someMethod();
  1. Verifying that a method was not called:

Mockito.verify(myMock, never()).someMethod();
  1. Verifying that a method was called with specific arguments:

Mockito.verify(myMock, times(1)).someMethod(argument1, argument2);

Advanced Features

  1. Mocking void methods:

Mockito.doNothing().when(myMock).someVoidMethod();
  1. Mocking static methods:

Mockito.mockStatic(MyClass.class);
Mockito.when(MyClass.someStaticMethod()).thenReturn(someValue);
Mockito.verifyStatic(MyClass.class, times(1));
MyClass.someStaticMethod();
Mockito.verifyNoMoreInteractions(MyClass.class);
  1. Mocking final methods:

MyClass myMock = Mockito.mock(MyClass.class);
Mockito.when(myMock.finalMethod()).thenCallRealMethod();

Matchers

Matchers allow developers to specify more complex argument matching for method calls on mock objects.

  1. Using argument matchers:

Mockito.when(myMock.someMethod(Mockito.anyString())).thenReturn(someValue);
  1. Combining matchers:

Mockito.when(myMock.someMethod(Mockito.argThat(
    Matchers.allOf(
        Matchers.startsWith("prefix"),
        Matchers.endsWith("suffix")
    )
))).thenReturn(someValue);

Annotations

  1. @Mock: Declares a mock object to be created and injected.

@Mock
private MyClass myMock;
  1. @InjectMocks: Injects the mocked dependencies into the class being tested.

@InjectMocks
private MyService myService;
  1. @RunWith(MockitoJUnitRunner.class): Runs the tests using the Mockito test runner.

@RunWith(MockitoJUnitRunner.class)
public class MyTest {
    ...
}

Last updated