Mockito Cheat Sheet for EasyMock users

Note: This document is continuously updated...last update Fri 22 May 2020

Q: How do I create a nice mock?

import static org.mockito.Mockito.mock;

@Before
public void setUp() {
  simulationMock = mock( Simulation.class );
}

Q: Can I use annotations to create Mocks and Captors?

@RunWith(MockitoJUnitRunner.class)
public class PlanetsGeneratorTest {

  @Mock
  private Simulation simulationMock = mock( Simulation.class );

  @Captor
  private ArgumentCaptor<List<Buildings>> buildingsCaptor;

Q: How do I add behavior to a mock?

import static org.mockito.Mockito.when;

@Test
public void testWithSpecificNumber() {
  when(simulationMock.getNextNumber().thenReturn( 1 );
  ...
}

Q: How do I verify that a method was called x times?

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@Test
public void testWithSpecificNumber() {
  verify(simulationMock, times(x)).getNextNumber();
  ...
}

Q: How-To simulate an exception is thrown

import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;

@Test
public void testWithExpectedException() {
  when(vanishedPlanet.buildSpacebar().thenThrow(new PlanetNotFoundException());
}

Q: Can Mockito stub a method without regard to the argument? A: Use the matcher notNull():

import static org.mockito.Matchers.notNull;
import static org.mockito.Mockito.when;

@Test
public void testWhenNotNullIsExpected() {
  when(androidKeystoreMock.getAndroidSha1( ( String )notNull() )).thenReturn( "01:23:...:ef" );
  ....
}

Q: How do I assert an actual value with AssertJ?

import static org.assertj.core.api.Assertions.assertThat;

@Test
public void testWhenResultIs42() {
  assertThat( actual.getNumber() ).isEqualTo( 42 );
}

Q: How do I verify void methods (e.g. public void doSomthing())?

verify(service, times(1)).doSomething();

Bonus: How can I simulate side-effects of a void method?

doAnswer(
        answer -> {
          String path = answer.getArgument(1, String.class);
          String filename = answer.getArgument(2, String.class);
          copy("test content".getBytes(UTF_8), Paths.get(pfad, dateiName).toFile());
          return null;
        })
        .when(this.planetsService)
        .downloadSummary(eq(42), notNull(), eq("test content"));

Q: How to I grep method arguments?

This is the times for a Mockito Spy