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