Sip of MoKito

    Do you know what a mock object is? No ?

    What Wikipedia says about this : “In object-oriented programming, a mock object imitates the behavior of a real object in a given way ...”. It would seem why? Wikipedia continues : “During unit testing, mock objects can simulate the behavior of business objects and business logic, which is sometimes necessary because of the complexity of real behavior.”

    And what do mock libraries give to a java developer? Of course, the convenience of creating and using those same mock objects! lists as many as 7 libraries:

    I started acquaintance with mock-objects from another library, which is not on - Mockito . I just trusted the opinion of javaposse , who recognized mockito as the library of the week, as well as the mood of the java blogosphere and was not disappointed. You will also appreciate how convenient it is:

    Attention! Having taken a sip - it is impossible to stop.

    Checking behavior

    The mock object will remember any calls to its methods, so that after you can check which methods your test code called for the mock object
    Copy Source | Copy HTML
    1. //статически импортируем методы (для красоты и легкости кода)
    2. import static org.mockito.Mockito.*;
    4. //вот он - mock-объект (заметьте: List.class - это интерфейс)
    5. List mockedList = mock(List.class);
    7. //используем его
    8. mockedList.add("one");
    9. mockedList.clear();
    11. //проверяем, были ли вызваны методы add с параметром "one" и clear
    12. verify(mockedList).add("one");
    13. verify(mockedList).clear();

    But what about stubs?

    By default, all methods of the mock object return default values, false for boolean, 0 for int, empty collections, null for other objects.
    Copy Source | Copy HTML
    1. //Вы можете создавать mock для конкретного класса, не только для интерфейса
    2. LinkedList mockedList = mock(LinkedList.class);
    4. //stub'инг
    5. when(mockedList.get(0)).thenReturn("first");
    6. when(mockedList.get(1)).thenThrow(new RuntimeException());
    8. //получим "first"
    9. System.out.println(mockedList.get(0));
    11. //получим RuntimeException
    12. System.out.println(mockedList.get(1));
    14. //получим "null" ибо get(999) не был определен
    15. System.out.println(mockedList.get(999));

    Checking the exact number of calls

    Copy Source | Copy HTML
    1. //используем mock-объект
    2. mockedList.add(«once»);
    4. mockedList.add(«twice»);
    5. mockedList.add(«twice»);
    7. mockedList.add(«three times»);
    8. mockedList.add(«three times»);
    9. mockedList.add(«three times»);
    11. //по умолчанию проверка, что вызывался 1 раз ~ times(1)
    12. verify(mockedList).add(«once»);
    13. verify(mockedList, times(1)).add(«once»);
    15. //точное число вызовов
    16. verify(mockedList, times(2)).add(«twice»);
    17. verify(mockedList, times(3)).add(«three times»);
    19. //никогда ~ never() ~ times(0)
    20. verify(mockedList, never()).add(«never happened»);
    22. //как минимум, как максимум
    23. verify(mockedList, atLeastOnce()).add(«three times»);
    24. verify(mockedList, atLeast(2)).add(«five times»);
    25. verify(mockedList, atMost(5)).add(«three times»);

    Parasitize on real objects

    You can create a mock object, (more precisely, a spy object) that will use the real object when calling the method. Overloading only the methods you need, so to speak a partial mock-object.
    Copy Source | Copy HTML
    1. List list = new LinkedList();
    2. List spy = spy(list);
    4. //опционально, определяем лишь метод size()
    5. when(spy.size()).thenReturn(100);
    7. //используем реальные методы
    8. spy.add("one");
    9. spy.add("two");
    11. //получим "one"
    12. System.out.println(spy.get(0));
    14. //метод size() нами переопределён - получим 100
    15. System.out.println(spy.size());
    17. //можем проверить
    18. verify(spy).add("one");
    19. verify(spy).add("two");


    • We use masks in arguments of redefined methods
    • Overriding methods returning void
    • Check the order of mock object calls
    • Looking for unnecessary mock object calls
    • Abstract Mock
    • Different return values ​​for the same arguments
    • ... the leftovers are sweet

    Additional literature:

    Thanks. And yes, the word mock is mentioned 58 times in this post.

    Also popular now: