基于Mockito的Android应用单元测试

本文详细介绍了Mockito库在Android应用单元测试中的使用方法,包括如何在AndroidStudio中添加依赖,以及通过不同方式创建和操作Mock对象。同时,文章还提供了具体的代码示例,如使用@Mock注解、MockitoRule和@RunWith运行器,以及如何验证方法调用和设置Mock对象的行为。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  • 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()));
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

wjxbless

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值