How can we mock a list?

import static org.mockito.Mockito.*;

// mock creation
List mockedList = mock(List.class);

// using mock object - it does not throw any "unexpected interaction" exception

// selective, explicit, highly readable verification

How can we mock method calls?

// you can mock concrete classes, not only interfaces
LinkedList mockedList = mock(LinkedList.class);

// stubbing appears before the actual execution

// the following prints "first"

// the following prints "null" because get(999) was not stubbed

What is the purpose of the mock() method?

create mock.

  • optionally specify how it should behave via Answer/ReturnValues/MockSettings
  • when()/given() to specify how a mock should behave
  • If the provided answers don’t fit your needs, write one yourself extending the Answer interface

What is the purpose of the spy() method?

partial mocking, real methods are invoked but still can be verified and stubbed

What is the purpose of the @InjectMocks annotation?

automatically inject mocks/spies fields annotated with @Spy or @Mock

What is the purpose of the verify() method?

  • to check methods were called with given arguments
  • can use flexible argument matching, for example any expression via the any()
  • or capture what arguments where called using @Captor instead

When should we not use mock?

  • Do not mock types you don’t own
  • Don’t mock value objects
  • Don’t mock everything
  • Show love with your tests!
Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License