本地单元测试中Build.VERSION.SDK_INT的存根值 [英] Stub value of Build.VERSION.SDK_INT in Local Unit Test

查看:429
本文介绍了本地单元测试中Build.VERSION.SDK_INT的存根值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否仍然可以存根Build.Version.SDK_INT的值?假设我在ClassUnderTest中有以下几行:

I am wondering if there is anyway to stub the value of Build.Version.SDK_INT? Suppose I have the following lines in the ClassUnderTest:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
    //do work
}else{
    //do another work
}

如何覆盖所有代码?

我的意思是我想使用不同的SDK_INT运行两个测试以输入两个模块.

I mean I want to run two tests with different SDK_INT to enter both blocks.

是否可以在Android 本地单元测试中使用Mockito/PowerMockito?

Is it possible in android local unit tests using Mockito/PowerMockito?

谢谢

推荐答案

使用反射更改值.

 static void setFinalStatic(Field field, Object newValue) throws Exception {
    field.setAccessible(true);

    Field modifiersField = Field.class.getDeclaredField("modifiers");
    modifiersField.setAccessible(true);
    modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);

    field.set(null, newValue);
 }

然后

 setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 123);

已通过测试.有效.

更新: 有一种更清洁的方法.

Update: There is a cleaner way to do it.

创建界面

interface BuildVersionProvider {

    fun currentVersion(): Int

}

实现界面

class BuildVersionProviderImpl : BuildVersionProvider {

    override fun currentVersion() = Build.VERSION.SDK_INT

}

每当您需要当前的构建版本时,就可以通过接口将该类作为构造函数参数注入.然后在测试时创建一个SUT(被测系统)对象.您可以自己实现该接口.这种处理方式可能是更多的代码,但遵循SOLID原则,并且可以为您提供可测试的代码,而不会弄乱反射和系统变量.

Inject this class as a constructor argument through the interface whenever you want current build version. Then in the tests when creating a SUT (System Under Test) object. You can implement the interface yourself. This way of doing things may be more code but follows the SOLID principles and gives you testable code without messing with reflection and system variables.

这篇关于本地单元测试中Build.VERSION.SDK_INT的存根值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆