In this tutorial, we'll illustrate how to make the most out of spies in Mockito.
We'll talk about the @Spy annotation and how to stub a spy. Finally, we'll go into the difference between Mock and Spy. Of course, for more Mockito goodness, have a look at the series here.
2. Simple Spy Example
Let's start with a simple example of how to use a spy.
Simply put, the API is Mockito.spy() (more) to spy on a real object. This will allow us to call all the normal methods of the object while still tracking every interaction, just as we would with a mock. Now let's do a quick example where we'll spy on an existing MyList object:
- public static class MyList {
- final List<String> innerList = new ArrayList<String>();
- public void add(String element) {
- innerList.add(element);
- }
- public int size() {return innerList.size();}
- }
- @Test
- public void whenSpyingOnList_thenCorrect() {
- MyList list = new MyList();
- MyList spyList = Mockito.spy(list);
- spyList.add("one");
- spyList.add("two");
- Mockito.verify(spyList).add("one");
- Mockito.verify(spyList).add("two");
- assertEquals(spyList.size(), 2);
- }
3. The @Spy Annotation
Next, let's see how to use the @Spy annotation. We can use the @Spy annotation instead of spy(). To enable Mockito annotations (such as @Spy, @Mock, … ), we need to do one of the following:
Then:
- @Spy
- MyList aSpyList = new MyList();
- @Test
- public void whenUsingTheSpyAnnotation_thenObjectIsSpied() {
- MockitoAnnotations.initMocks(this);
- aSpyList.add("one");
- aSpyList.add("two");
- Mockito.verify(aSpyList).add("one");
- Mockito.verify(aSpyList).add("two");
- assertEquals(aSpyList.size(), 2);
- }
4. Stubbing a Spy
Now let's see how to stub a Spy. We can configure/override the behavior of a method using the same syntax we would use with a mock.
Here we'll use doReturn() to override the size() method:
- @Test
- public void whenStubASpy_thenStubbed() {
- MyList list = new MyList();
- MyList spyList = Mockito.spy(list);
- assertEquals(0, spyList.size());
- Mockito.doReturn(100).when(spyList).size();
- assertEquals(spyList.size(), 100);
- }
5. Mock vs Spy in Mockito
Let's discuss the difference between Mock and Spy in Mockito. We won't examine the theoretical differences between the two concepts, just how they differ within Mockito itself.
When Mockito creates a mock, it does so from the Class of a Type, not from an actual instance. The mock simply creates a bare-bones shell instance of the Class, entirely instrumented to track interactions with it. On the other hand, the spy will wrap an existing instance. It will still behave in the same way as the normal instance; the only difference is that it will also be instrumented to track all the interactions with it.
Here we'll create a mock of the MyList class:
- @Test
- public void whenCreateMock_thenCreated() {
- MyList mockedList = Mockito.mock(MyList.class);
- mockedList.add("one");
- Mockito.verify(mockedList).add("one");
- assertEquals(0, mockedList.size());
- }
- @Test
- public void whenCreateSpy_thenCreate() {
- MyList spyList = Mockito.spy(new MyList());
- spyList.add("one");
- Mockito.verify(spyList).add("one");
- assertEquals(1, spyList.size());
- }
6. Understanding the Mockito NotAMockException
In this final section, we'll learn about the Mockito NotAMockException. This exception is one of the common exceptions we will likely encounter when misusing mocks or spies.
Let's start by understanding the circumstances in which this exception can occur:
- List<String> list = new ArrayList<String>();
- Mockito.doReturn(100).when(list).size();
- org.mockito.exceptions.misusing.NotAMockException:
- Argument passed to when() is not a mock!
- Example of correct stubbing:
- doThrow(new RuntimeException()).when(mock).someMethod();
As we can also see, the Exception message even describes what a correct invocation should look like. Now that we have a better understanding of what the problem is, let's fix it by following the recommendation:
- final List<String> spyList = Mockito.spy(new ArrayList<>());
- assertThatNoException().isThrownBy(() -> Mockito.doReturn(100).when(spyList).size());