Mockito

junit

https://github.com/mockito/mockito
https://dzone.com/refcardz/mockito
http://site.mockito.org/
http://www.vogella.com/articles/Mockito/article.html
http://java.dzone.com/articles/5-minute-mockito-tutorial-howto
https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/BDDMockito.html
https://github.com/linkedin/dexmaker
http://refcardz.dzone.com/refcardz/mockito
https://static.javadoc.io/org.mockito/mockito-core/2.2.29/org/mockito/ArgumentMatchers.html
https://static.javadoc.io/org.mockito/mockito-core/2.2.29/org/mockito/Mockito.html#21
https://dzone.com/refcardz/mockito
https://static.javadoc.io/org.mockito/mockito-core/2.7.22/org/mockito/Mockito.html

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
mockedList.add("one");
mockedList.clear();

// selective, explicit, highly readable verification
verify(mockedList).add("one");
verify(mockedList).clear();

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
when(mockedList.get(0)).thenReturn("first");

// the following prints "first"
System.out.println(mockedList.get(0));

// the following prints "null" because get(999) was not stubbed
System.out.println(mockedList.get(999));

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