Home

irynasokolova edited this page Nov 30, 2016 · 14 revisions

Mockito

Mockito is a mocking framework for unit tests in Java. It has been designed to be intuitive to use when the test needs mocks.

  • Simple usage : stub, use, verify
  • Programatic creation of mocks via mock() or spy()
  • Programmatic stubbing via
    • Mockito.when(mock.action()).thenReturn(true)
    • BDDMockito.given(mock.action()).willReturn(true)
  • Customize mock answer or provide your own
  • Programmatic verification via
    • Mockito.verify(mock).action()
    • BDDMockito.then(mock).should().action()
  • Annotation sugar via @Mock, @Spy, @Captor or @InjectMocks
  • JUnit first class support via the runner MockitoJUnitRunner and the now favored rule MockitoJUnit.rule()

Remember

  • Do not mock types you don't own
  • Don't mock value objects
  • Don't mock everything
  • Show some love with your tests

Examples

// You can mock concrete classes and interfaces
TrainSeats seats = mock(TrainSeats.class);

// stubbing appears before the actual execution
when(seats.book(Seat.near(WINDOW).in(FIRST_CLASS))).thenReturn(BOOKED);

// the following prints "BOOKED"
System.out.println(seats.book(Seat.near(WINDOW).in(FIRST_CLASS)));

// the following prints "null" because 
// .book(Seat.near(AISLE).in(FIRST_CLASS))) was not stubbed
System.out.println(seats.book(Seat.near(AISLE).in(FIRST_CLASS)));

// the following verification passes because 
// .book(Seat.near(WINDOW).in(FIRST_CLASS)) has been invoked
verify(seats).book(Seat.near(WINDOW).in(FIRST_CLASS))

// the following verification fails because 
// .book(Seat.in(SECOND_CLASS)) has not been invoked
verify(seats).book(Seat.in(SECOND_CLASS))

The BDD way :

// You can mock concrete classes and interfaces
TrainSeats seats = mock(TrainSeats.class);

// stubbing appears before the actual execution
given(seats.book(Seat.near(WINDOW).in(FIRST_CLASS))).willReturn(BOOKED);

// the following prints "BOOKED"
System.out.println(seats.book(Seat.near(WINDOW).in(FIRST_CLASS)));

// the following prints "null" because 
// .book(Seat.near(AISLE).in(FIRST_CLASS))) was not stubbed
System.out.println(seats.book(Seat.near(AISLE).in(FIRST_CLASS)));

// the following verification passes because 
// .book(Seat.near(WINDOW).in(FIRST_CLASS)) has been invoked
then(seats).should().book(Seat.near(WINDOW).in(FIRST_CLASS))

// the following verification fails because 
// .book(Seat.in(SECOND_CLASS)) has not been invoked
then(seats).should().book(Seat.in(SECOND_CLASS))

More