基于Mockito的Android应用单元测试
原创
©著作权归作者所有:来自51CTO博客作者wx5ba8dc11102bc的原创作品,请联系作者获取转载授权,否则将追究法律责任
- 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);
}
}
public class MckitoTest {
@Mock
Person person;
@Rule
public MockitoRule mockitoRule = MockitoJUnit.rule();
@Test
public void testMockito(){
assertNotNull(person);
}
}
- Mock出的对象中非void方法都将返回默认值,比如int方法将返回0,对象方法将返回null等,而void方 法将什么都不
- 要改变Mock对象的默认行为,需要通过对Mock对象进行操作来完成‘
//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);
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();
}
- 是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()));