- Mockito是java 开发中常用的Mock库,在Android应用单元测试中比较常见
- 在实际的单元测试中,测试的类之间会有或多或少的耦合,导致无法顺利的进行测试,这是就可以使用Mockito,该库可以模拟Mock对象,体换原先以来的真是独享,这样就可以避免外部影响,只测试本类
- 在Android Studio中添加依赖:
dependencies {
testImplementation 'org.mockito:mockito-core:2.11.0'
androidTestImplementation 'org.mockito:mockito-android:2.11.0'
}
- 普通方法:
@Testpublic void testMock(){
Person person= mock(Person.class);
assertNotNull(person);
}
- 注解方法
public class MockitoTest{
@Mock
Person person;
@Before
public void setUp(){
//初始化
MockitoAnnotations.initMocks(this);
}
@Test
public void testIsNotNull(){
assertNotNull(person);
}
}
- 运行器方法
@RunWith(MockitoJUnitRunner.class)public class MckitoTest {
@Mock
Person person;
@Test
public void testMockito(){
assertNotNull(person);
}
}
- MockitoRule方法:
public class MckitoTest {
@Mock
Person person;
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Test
public void testMockito(){
assertNotNull(person);
}
}
- Mockito:对Mock对象进行操作的方法
- Mock出的对象中非void方法都将返回默认值,比如int方法将返回0,对象方法将返回null等,而void方 法将什么都不
- 要改变Mock对象的默认行为,需要通过对Mock对象进行操作来完成‘
- when thenReturn:
//Mockito对对象的操作
//when调用某个方法,thenReturn预期返回值
Comparable<Integer> comparable = mock(Comparable.class);
when(comparable.compareTo(anyInt())).thenReturn(-1);
assertEquals(-1, comparable.compareTo(3));
Comparable<Person> comparable1 = mock(Comparable.class);
when(comparable1.compareTo(isA(Person.class))).thenReturn(1);
assertEquals(1, comparable1.compareTo(new Person()));
Iterator<String> i = mock(Iterator.class);
when(i.next()).thenReturn("Mockito").thenReturn("mocks");
String result = i.next() + " " +i.next();
assertEquals("Mockito mocks",result);
- when thenThrow:
Properties properties = mock(Properties.class);
Person person= new Person();when(properties.get("wjx")).thenThrow(new IllegalArgumentException("error"));
try{
properties.get("wjx");
fail("is missed");
}catch (IllegalArgumentException e){
e.printStackTrace();
}
- 验证(verify):
- 是Mock区别于其他TestDouble的特别之处
- 检验方法是否被正确调用过,调用情况等
Person person = mock(Person.class);
when(person.getName()).thenReturn("wjx");
person.setName("wjx");
person.getName();
//验证参数
verify(person).setName(ArgumentMatchers.eq("wjx"));
//验证执行次数
verify(person, times(1)).getName();
- 但是Mockito也存在一些限制(不能Mock):
- 下面是可以在桩上调用的方法
- Static class
- Final class
- Anonymous class
- Primitive type
when(daoMock.save(any(Custom.class))).thenReturn(new Custom());
final Custom custom = new Custom();
assertThat(service.addCustom(custom), is(notNullValue()));
daoMock daoMock = mock(com.example.adminstator.myapplication.whenThenAnswer.daoMock.class);
when(daoMock.save(any(Custom.class))).thenAnswer(new Answer<Custom>() {
@Override
public Custom answer(InvocationOnMock invocation) throws Throwable {
Object[] arguments = invocation.getArguments();
if(arguments!=null&&arguments.length>0 &&arguments[0]!=null){
Custom custom1 = (Custom)arguments[0];
custom1.setId(1);
return custom1;
}
return null;
}
});
Custom custom1 = new Custom();assertThat(service.addCustom(custom1), is(notNullValue()));