2022年9月24日 星期六

[Mockito] Using Spies

 article source

1. Overview
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:
  1. public static class MyList {  
  2.     final List<String> innerList = new ArrayList<String>();  
  3.     public void add(String element) {  
  4.         innerList.add(element);  
  5.     }  
  6.     public int size() {return innerList.size();}  
  7. }  
  8.   
  9. @Test  
  10. public void whenSpyingOnList_thenCorrect() {  
  11.     MyList list = new MyList();  
  12.     MyList spyList = Mockito.spy(list);  
  13.   
  14.     spyList.add("one");  
  15.     spyList.add("two");  
  16.   
  17.     Mockito.verify(spyList).add("one");  
  18.     Mockito.verify(spyList).add("two");  
  19.   
  20.     assertEquals(spyList.size(), 2);          
  21. }  
Note how the real method add() is actually called and how the size of spyList becomes 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:
* Call the method MockitoAnnotations.initMocks(this) to initialize annotated fields
* Use the built-in runner @RunWith(MockitoJUnitRunner.class)

Then:
  1. @Spy  
  2. MyList aSpyList = new MyList();  
  3.   
  4. @Test  
  5. public void whenUsingTheSpyAnnotation_thenObjectIsSpied() {  
  6.     MockitoAnnotations.initMocks(this);  
  7.       
  8.     aSpyList.add("one");  
  9.     aSpyList.add("two");  
  10.   
  11.     Mockito.verify(aSpyList).add("one");  
  12.     Mockito.verify(aSpyList).add("two");  
  13.   
  14.     assertEquals(aSpyList.size(), 2);  
  15. }  

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:
  1. @Test  
  2. public void whenStubASpy_thenStubbed() {  
  3.     MyList list = new MyList();  
  4.     MyList spyList = Mockito.spy(list);  
  5.   
  6.     assertEquals(0, spyList.size());  
  7.   
  8.     Mockito.doReturn(100).when(spyList).size();  
  9.     assertEquals(spyList.size(), 100);  
  10. }  

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:
  1. @Test  
  2. public void whenCreateMock_thenCreated() {  
  3.     MyList mockedList = Mockito.mock(MyList.class);  
  4.   
  5.     mockedList.add("one");  
  6.     Mockito.verify(mockedList).add("one");  
  7.   
  8.     assertEquals(0, mockedList.size());  
  9. }  
As we can see, adding an element into the mocked list doesn't actually add anything; it just calls the method with no other side effects. A spy, on the other hand, will behave differently; it will actually call the real implementation of the add method and add the element to the underlying list:
  1. @Test  
  2. public void whenCreateSpy_thenCreate() {  
  3.     MyList spyList = Mockito.spy(new MyList());  
  4.   
  5.     spyList.add("one");  
  6.     Mockito.verify(spyList).add("one");  
  7.   
  8.     assertEquals(1, spyList.size());  
  9. }  

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:
  1. List<String> list = new ArrayList<String>();  
  2. Mockito.doReturn(100).when(list).size();  
When we run this code snippet, we'll get the following error:
  1. org.mockito.exceptions.misusing.NotAMockException:   
  2. Argument passed to when() is not a mock!  
  3. Example of correct stubbing:  
  4.     doThrow(new RuntimeException()).when(mock).someMethod();  
Thankfully, it is quite clear from the Mockito error message what the problem is here. In our example, the list object is not a mock. The Mockito when() method expects a mock or spy object as the argument.

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:
  1. final List<String> spyList = Mockito.spy(new ArrayList<>());  
  2. assertThatNoException().isThrownBy(() -> Mockito.doReturn(100).when(spyList).size());  
Our example now behaves as expected, and we no longer see the Mockito NotAMockException.

沒有留言:

張貼留言

[Git 常見問題] error: The following untracked working tree files would be overwritten by merge

  Source From  Here 方案1: // x -----删除忽略文件已经对 git 来说不识别的文件 // d -----删除未被添加到 git 的路径中的文件 // f -----强制运行 #   git clean -d -fx 方案2: 今天在服务器上  gi...