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.

2022年9月16日 星期五

[Mockito] Getting Started with Mockito @Mock, @Spy, @Captor and @InjectMocks

 article source

1. Overview
In this tutorial, we'll cover the following annotations of the Mockito library: @Mock@Spy@Captor, and @InjectMocks. For more Mockito goodness, have a look at the series here.

2. Enable Mockito Annotations
Before we go further, let's explore different ways to enable the use of annotations with Mockito tests.

MockitoJUnitRunner
The first option we have is to annotate the JUnit test with a MockitoJUnitRunner:
  1. @RunWith(MockitoJUnitRunner.class)  
  2. public class MockitoAnnotationTest {  
  3.     ...  
  4. }  
MockitoAnnotations.openMocks()
Alternatively, we can enable Mockito annotations programmatically by invoking MockitoAnnotations.openMocks():
  1. @Before  
  2. public void init() {  
  3.     MockitoAnnotations.openMocks(this);  
  4. }  
MockitoJUnit.rule()
Lastly, we can use a MockitoJUnit.rule():
  1. public class MockitoInitWithMockitoJUnitRuleUnitTest {  
  2.   
  3.     @Rule  
  4.     public MockitoRule initRule = MockitoJUnit.rule();  
  5.   
  6.     ...  
  7. }  
In this case, we must remember to make our rule public.

3. @Mock Annotation
The most widely used annotation in Mockito is @Mock. We can use @Mock to create and inject mocked instances without having to call Mockito.mock manually. In the following example, we'll create a mocked ArrayList manually without using the @Mock annotation:
  1. @Test  
  2. public void whenNotUseMockAnnotation_thenCorrect() {  
  3.     List mockList = Mockito.mock(ArrayList.class);  
  4.       
  5.     mockList.add("one");  
  6.     Mockito.verify(mockList).add("one");  
  7.     assertEquals(0, mockList.size());  
  8.   
  9.     Mockito.when(mockList.size()).thenReturn(100);  
  10.     assertEquals(100, mockList.size());  
  11. }  

Now we'll do the same, but we'll inject the mock using the @Mock annotation:
  1. @Rule  
  2. public MockitoRule initRule = MockitoJUnit.rule();  
  3.   
  4. @Mock  
  5. List<String> mockedList;  
  6.   
  7. @Test  
  8. public void whenUseMockAnnotation_thenMockIsInjected() {  
  9.     mockedList.add("one");  
  10.     Mockito.verify(mockedList).add("one");  
  11.     assertEquals(0, mockedList.size());  
  12.   
  13.     Mockito.when(mockedList.size()).thenReturn(100);  
  14.     assertEquals(100, mockedList.size());  
  15. }  
Note how in both examples, we're interacting with the mock and verifying some of these interactions, just to make sure that the mock is behaving correctly.

4. @Spy Annotation
Now let's see how to use the @Spy annotation to spy on an existing instance.

In the following example, we create a spy of a List without using the @Spy annotation:
  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 whenNotUseSpyAnnotation_thenCorrect() {  
  11.     MyList spyList = Mockito.spy(new UsingMockAnnotTest.MyList());  
  12.       
  13.     spyList.add("one");  
  14.     spyList.add("two");  
  15.   
  16.     Mockito.verify(spyList).add("one");  
  17.     Mockito.verify(spyList).add("two");  
  18.   
  19.     assertEquals(2, spyList.size());  
  20.   
  21.     Mockito.doReturn(100).when(spyList).size();  
  22.     assertEquals(100, spyList.size());  
  23. }  
Now we'll do the same thing, spy on the list, but we'll use the @Spy annotation:
  1. @Spy  
  2. MyList spiedList = new MyList();  
  3.   
  4. @Test  
  5. public void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {  
  6.     spiedList.add("one");  
  7.     spiedList.add("two");  
  8.   
  9.     Mockito.verify(spiedList).add("one");  
  10.     Mockito.verify(spiedList).add("two");  
  11.   
  12.     assertEquals(2, spiedList.size());  
  13.   
  14.     Mockito.doReturn(100).when(spiedList).size();  
  15.     assertEquals(100, spiedList.size());  
  16. }  
Note how, as before, we're interacting with the spy here to make sure that it behaves correctly. In this example we:
* Used the real method spiedList.add() to add elements to the spiedList.
* Stubbed the method spiedList.size() to return 100 instead of 2 using Mockito.doReturn().

5. @Captor Annotation
Next let's see how to use the @Captor annotation to create an ArgumentCaptor instance.

In the following example, we'll create an ArgumentCaptor without using the @Captor annotation:
  1. @Test  
  2. public void whenNotUseCaptorAnnotation_thenCorrect() {  
  3.     MyList mockList = Mockito.mock(MyList.class);  
  4.     ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);  
  5.   
  6.     mockList.add("one");  
  7.     Mockito.verify(mockList).add(arg.capture());  
  8.   
  9.     assertEquals("one", arg.getValue());  
  10. }  
Now let's make use of @Captor for the same purpose, to create an ArgumentCaptor instance:
  1. @Mock  
  2. MyList mockedList2;  
  3.   
  4. @Captor   
  5. ArgumentCaptor<String> argCaptor;  
  6.   
  7. @Test  
  8. public void whenUseCaptorAnnotation_thenTheSam() {  
  9.     mockedList2.add("one");  
  10.     Mockito.verify(mockedList2).add(argCaptor.capture());  
  11.   
  12.     assertEquals("one", argCaptor.getValue());  
  13. }  
Notice how the test becomes simpler and more readable when we take out the configuration logic.

6. @InjectMocks Annotation
Now let's discuss how to use the @InjectMocks annotation to inject mock fields into the tested object automatically.

In the following example, we'll use @InjectMocks to inject the mock wordMap into the MyDictionary dic. Here is the class MyDictionary:
  1. public static class MyDictionary {  
  2.     Map<String, String> wordMap;  
  3.   
  4.     public MyDictionary() {  
  5.         wordMap = new HashMap<String, String>();  
  6.     }  
  7.     public void add(final String word, final String meaning) {  
  8.         wordMap.put(word, meaning);  
  9.     }  
  10.     public String getMeaning(final String word) {  
  11.         return wordMap.get(word);  
  12.     }  
  13. }  
Then is our unit test case:
  1. @Mock  
  2. Map<String, String> wordMap;  
  3.   
  4. @InjectMocks  
  5. MyDictionary dic = new MyDictionary();  
  6.   
  7. @Test  
  8. public void whenUseInjectMocksAnnotation_thenCorrect() {  
  9.     Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");  
  10.   
  11.     assertEquals("aMeaning", dic.getMeaning("aWord"));  
  12. }  
7. Injecting a Mock Into a Spy
Similar to the above test, we might want to inject a mock into a spy:
  1. @Mock  
  2. Map<String, String> wordMap;  
  3.   
  4. @Spy  
  5. MyDictionary spyDic = new MyDictionary();  
However, Mockito doesn't support injecting mocks into spies, and the following test results in an exception:
  1. @Test   
  2. public void whenUseInjectMocksAnnotation_thenCorrect() {   
  3.     Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");   
  4.   
  5.     assertEquals("aMeaning", spyDic.getMeaning("aWord"));   
  6. }  
If we want to use a mock with a spy, we can manually inject the mock through a constructor:
  1. MyDictionary(Map<String, String> wordMap) {  
  2.     this.wordMap = wordMap;  
  3. }  
Instead of using the annotation, we can now create the spy manually:
  1. public static class MyDictionary {  
  2.     Map<String, String> wordMap;  
  3.       
  4.     public MyDictionary(Map<String, String> aMap) {  
  5.         this.wordMap = aMap;  
  6.     }  
  7.   
  8.     public MyDictionary() {  
  9.         wordMap = new HashMap<String, String>();  
  10.     }  
  11.     public void add(final String word, final String meaning) {  
  12.         wordMap.put(word, meaning);  
  13.     }  
  14.     public String getMeaning(final String word) {  
  15.         return wordMap.get(word);  
  16.     }  
  17. }  
  18.   
  19. @Mock    
  20. Map<String, String> mockWordMap;  
  21.   
  22. @Test   
  23. public void whenUseInjectMocksAnnotation_thenCorrectPart2() {   
  24.     MyDictionary spyDic = Mockito.spy(new MyDictionary(mockWordMap));  
  25.     Mockito.when(mockWordMap.get("aWord")).thenReturn("aMeaning");   
  26.   
  27.     assertEquals("aMeaning", spyDic.getMeaning("aWord"));   
  28. }  
The test will now pass.

8. Running Into NPE While Using Annotation
Often we may run into NullPointerException when we try to actually use the instance annotated with @Mock or @Spy:
  1. public class MockitoAnnotationsUninitializedUnitTest {  
  2.   
  3.     @Mock  
  4.     List<String> mockedList;  
  5.   
  6.     @Test(expected = NullPointerException.class)  
  7.     public void whenMockitoAnnotationsUninitialized_thenNPEThrown() {  
  8.         Mockito.when(mockedList.size()).thenReturn(1);  
  9.     }  
  10. }  
Most of the time, this happens simply because we forget to properly enable Mockito annotations.

So we have to keep in mind that each time we want to use Mockito annotations, we must take the extra step and initialize them as we already explained earlier.

[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...