一、@Mock和@InjectMocks
@InjectMocks 通常加在被测试对象上。 该对象不会被mock,会创建真实的对象,把其他Mock的对象注入被测试对象上
@Mock 标注的对象对生成一个假的对象
二、Subbing和Assert
对于以下语法请参照例子:
when…thenReturn,when…thenThrow, when…thenAnswer, when…thenCallRealMethod
doReturn, doThrow, doNothing
Assert:assertEquals, assertThrows
@RunWith(MockitoJUnitRunner.class)
public class SubbingTest {
@Mock
private List<String> list;
@Test
public void how_to_use_subbing(){
//return时thenReturn和doReturn功能一样
Mockito.when(list.get(0)).thenReturn("first");
Mockito.doReturn("second").when(list).get(1);
Assert.assertEquals("first", list.get(0));
Assert.assertEquals("second", list.get(1));
//有返回值throw时用thenThrow
Mockito.when(list.get(Mockito.anyInt())).thenThrow(new RuntimeException());
try {
list.get(0);
fail();
}catch (Exception e){
Assert.assertThrows(RuntimeException.class,()->list.get(0));
}
}
@Test
public void how_to_subbing_return_void_method(){
//对无返回值的方法Mock
Mockito.doNothing().when(list).clear();
list.clear();
Mockito.verify(list,Mockito.times(1)).clear();
//无返回值throw时用doThrow
Mockito.doThrow(RuntimeException.