Mockito Cheat Sheet for EasyMock users

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: 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();
Show Comments