Mockito.mock()

Creates a mock of any non final class

Creates a mock of any class. By default, it will return default value for methods and fields when not mocked.

For Example: Primitive data types such as byte, short, int, long, float, double, boolean and char will return default value i.e 0 or false

Non-primitive data types such as String, Arrays and Classes return null when they are not mocked.

// with annotation
@Mock
private ClassName mock;

// Or with static method
final ClassName mock = Mockito.mock(ClassName.class);

// mock methods that returns something
Mockito.when(mock.sampleMethod()).thenReturn(sampleVal);

// mock method to throw Exception
Mockito.when(mock.sampleMethod()).thenThrow(SampleException.class);

// Mock void methods
Mockito.doNothing().when(mock).method();

// you can get invocation parameters with .thenAnswer()
Mockito.when(mock.sampleMethod(Mockito.any(OtherClass.class))).thenAnswer((Answer<ThirdClass>) invocation -> {
      final OtherClass parameter1 = invocation.getArgument(0);
      return thirdClassObject; 
});

// Verify interactions
Mockito.verify(mock, Mockito.times(1)).sampleMethod();

// Verify, method should not be invoked even once
Mockito.verify(mock, Mockito.never()).sampleMethod2();

// Verify, no methods should be called on given mock
Mockito.verifyNoMoreInteractions(otherMockedClass);

Last updated