
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!
java-source.net lists as many as 7 libraries:
I started acquaintance with mock-objects from another library, which is not on java-source.net - 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.
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
By default, all methods of the mock object return default values, false for boolean, 0 for int, empty collections, null for other 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.
Additional literature:
Thanks. And yes, the word mock is mentioned 58 times in this post.
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!
java-source.net lists as many as 7 libraries:
I started acquaintance with mock-objects from another library, which is not on java-source.net - 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- //статически импортируем методы (для красоты и легкости кода)
- import static org.mockito.Mockito.*;
-
- //вот он - mock-объект (заметьте: List.class - это интерфейс)
- List mockedList = mock(List.class);
-
- //используем его
- mockedList.add("one");
- mockedList.clear();
-
- //проверяем, были ли вызваны методы add с параметром "one" и clear
- verify(mockedList).add("one");
- 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- //Вы можете создавать mock для конкретного класса, не только для интерфейса
- LinkedList mockedList = mock(LinkedList.class);
-
- //stub'инг
- when(mockedList.get(0)).thenReturn("first");
- when(mockedList.get(1)).thenThrow(new RuntimeException());
-
- //получим "first"
- System.out.println(mockedList.get(0));
-
- //получим RuntimeException
- System.out.println(mockedList.get(1));
-
- //получим "null" ибо get(999) не был определен
- System.out.println(mockedList.get(999));
Checking the exact number of calls
Copy Source | Copy HTML- //используем mock-объект
- mockedList.add(«once»);
-
- mockedList.add(«twice»);
- mockedList.add(«twice»);
-
- mockedList.add(«three times»);
- mockedList.add(«three times»);
- mockedList.add(«three times»);
-
- //по умолчанию проверка, что вызывался 1 раз ~ times(1)
- verify(mockedList).add(«once»);
- verify(mockedList, times(1)).add(«once»);
-
- //точное число вызовов
- verify(mockedList, times(2)).add(«twice»);
- verify(mockedList, times(3)).add(«three times»);
-
- //никогда ~ never() ~ times(0)
- verify(mockedList, never()).add(«never happened»);
-
- //как минимум, как максимум
- verify(mockedList, atLeastOnce()).add(«three times»);
- verify(mockedList, atLeast(2)).add(«five times»);
- 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- List list = new LinkedList();
- List spy = spy(list);
-
- //опционально, определяем лишь метод size()
- when(spy.size()).thenReturn(100);
-
- //используем реальные методы
- spy.add("one");
- spy.add("two");
-
- //получим "one"
- System.out.println(spy.get(0));
-
- //метод size() нами переопределён - получим 100
- System.out.println(spy.size());
-
- //можем проверить
- verify(spy).add("one");
- verify(spy).add("two");
And
- 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:
- Comparison of Mockito and its most similar EasyMock
- InfoQ library overview
- Choosing the best mock library on stackoverflow
- mockobjects.com
Thanks. And yes, the word mock is mentioned 58 times in this post.