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:
- @RunWith(MockitoJUnitRunner.class)
- public class MockitoAnnotationTest {
- ...
- }
Alternatively, we can enable Mockito annotations programmatically by invoking MockitoAnnotations.openMocks():
- @Before
- public void init() {
- MockitoAnnotations.openMocks(this);
- }
Lastly, we can use a MockitoJUnit.rule():
- public class MockitoInitWithMockitoJUnitRuleUnitTest {
- @Rule
- public MockitoRule initRule = MockitoJUnit.rule();
- ...
- }
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:
- @Test
- public void whenNotUseMockAnnotation_thenCorrect() {
- List mockList = Mockito.mock(ArrayList.class);
- mockList.add("one");
- Mockito.verify(mockList).add("one");
- assertEquals(0, mockList.size());
- Mockito.when(mockList.size()).thenReturn(100);
- assertEquals(100, mockList.size());
- }
Now we'll do the same, but we'll inject the mock using the @Mock annotation:
- @Rule
- public MockitoRule initRule = MockitoJUnit.rule();
- @Mock
- List<String> mockedList;
- @Test
- public void whenUseMockAnnotation_thenMockIsInjected() {
- mockedList.add("one");
- Mockito.verify(mockedList).add("one");
- assertEquals(0, mockedList.size());
- Mockito.when(mockedList.size()).thenReturn(100);
- assertEquals(100, mockedList.size());
- }
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:
- 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 whenNotUseSpyAnnotation_thenCorrect() {
- MyList spyList = Mockito.spy(new UsingMockAnnotTest.MyList());
- spyList.add("one");
- spyList.add("two");
- Mockito.verify(spyList).add("one");
- Mockito.verify(spyList).add("two");
- assertEquals(2, spyList.size());
- Mockito.doReturn(100).when(spyList).size();
- assertEquals(100, spyList.size());
- }
- @Spy
- MyList spiedList = new MyList();
- @Test
- public void whenUseSpyAnnotation_thenSpyIsInjectedCorrectly() {
- spiedList.add("one");
- spiedList.add("two");
- Mockito.verify(spiedList).add("one");
- Mockito.verify(spiedList).add("two");
- assertEquals(2, spiedList.size());
- Mockito.doReturn(100).when(spiedList).size();
- assertEquals(100, spiedList.size());
- }
* 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:
- @Test
- public void whenNotUseCaptorAnnotation_thenCorrect() {
- MyList mockList = Mockito.mock(MyList.class);
- ArgumentCaptor<String> arg = ArgumentCaptor.forClass(String.class);
- mockList.add("one");
- Mockito.verify(mockList).add(arg.capture());
- assertEquals("one", arg.getValue());
- }
- @Mock
- MyList mockedList2;
- @Captor
- ArgumentCaptor<String> argCaptor;
- @Test
- public void whenUseCaptorAnnotation_thenTheSam() {
- mockedList2.add("one");
- Mockito.verify(mockedList2).add(argCaptor.capture());
- assertEquals("one", argCaptor.getValue());
- }
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:
- public static class MyDictionary {
- Map<String, String> wordMap;
- public MyDictionary() {
- wordMap = new HashMap<String, String>();
- }
- public void add(final String word, final String meaning) {
- wordMap.put(word, meaning);
- }
- public String getMeaning(final String word) {
- return wordMap.get(word);
- }
- }
- @Mock
- Map<String, String> wordMap;
- @InjectMocks
- MyDictionary dic = new MyDictionary();
- @Test
- public void whenUseInjectMocksAnnotation_thenCorrect() {
- Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
- assertEquals("aMeaning", dic.getMeaning("aWord"));
- }
Similar to the above test, we might want to inject a mock into a spy:
- @Mock
- Map<String, String> wordMap;
- @Spy
- MyDictionary spyDic = new MyDictionary();
- @Test
- public void whenUseInjectMocksAnnotation_thenCorrect() {
- Mockito.when(wordMap.get("aWord")).thenReturn("aMeaning");
- assertEquals("aMeaning", spyDic.getMeaning("aWord"));
- }
- MyDictionary(Map<String, String> wordMap) {
- this.wordMap = wordMap;
- }
- public static class MyDictionary {
- Map<String, String> wordMap;
- public MyDictionary(Map<String, String> aMap) {
- this.wordMap = aMap;
- }
- public MyDictionary() {
- wordMap = new HashMap<String, String>();
- }
- public void add(final String word, final String meaning) {
- wordMap.put(word, meaning);
- }
- public String getMeaning(final String word) {
- return wordMap.get(word);
- }
- }
- @Mock
- Map<String, String> mockWordMap;
- @Test
- public void whenUseInjectMocksAnnotation_thenCorrectPart2() {
- MyDictionary spyDic = Mockito.spy(new MyDictionary(mockWordMap));
- Mockito.when(mockWordMap.get("aWord")).thenReturn("aMeaning");
- assertEquals("aMeaning", spyDic.getMeaning("aWord"));
- }
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:
- public class MockitoAnnotationsUninitializedUnitTest {
- @Mock
- List<String> mockedList;
- @Test(expected = NullPointerException.class)
- public void whenMockitoAnnotationsUninitialized_thenNPEThrown() {
- Mockito.when(mockedList.size()).thenReturn(1);
- }
- }
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.
沒有留言:
張貼留言