@Mock, @Spy和 @InjectMocks快速使用指南

2019-04-14  本文已影响0人  一路花开_8fab

该系列文章翻译自https://www.baeldung.com/mockito-series

1.如何使Mockito的注解生效

方法1:给被测类添加@RunWith(MockitoJUnitRunner.class)注解

@RunWith(MockitoJUnitRunner.class)
public class MockitoAnnotationTest {
    ...
}

方法2:在初始化方法中使用MockitoAnnotations.initMocks(this)

@Before
public void init() {
    MockitoAnnotations.initMocks(this);
}

2.@Mock注解

@Mock用于代替Mockito.mock创建mock对象。
使用Mockito.mock的例子如下:

@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());
}

使用@Mock的例子如下:

@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());
}

3.@Spy注解

@Spy注解用于替代Mockito.spy创建spy对象
使用Mockito.spy例子如下:

@Test
public void whenNotUseSpyAnnotation_thenCorrect() {
    List<String> spyList = Mockito.spy(new ArrayList<String>());
     
    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例子如下:

@Spy
List<String> spiedList = new ArrayList<String>();
 
@Test
public void whenUseSpyAnnotation_thenSpyIsInjected() {
    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());
}

4.@InjectMocks注解

@InjectMocks用于自动注入@Spy和@Mock标注的对象,举例如下:

@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"));
}

MyDictionary类的定义如下:

public 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);
    }
}
上一篇 下一篇

猜你喜欢

热点阅读