本地单元测试中 Build.VERSION.SDK_INT 的存根值

2023-02-17移动开发问题
9

本文介绍了本地单元测试中 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 local 单元测试中是否可以使用 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);

经过测试.有效.

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

创建接口

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 的存根值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

硬件音量按钮更改应用程序音量
Hardware Volume buttons change in app volume(硬件音量按钮更改应用程序音量)...
2024-08-12 移动开发问题
10

Cocos2d - 如何检查不同层中对象之间的交集
Cocos2d - How to check for Intersection between objects in different layers(Cocos2d - 如何检查不同层中对象之间的交集)...
2024-08-12 移动开发问题
8

恢复游戏 cocos2d
Resume game cocos2d(恢复游戏 cocos2d)...
2024-08-12 移动开发问题
6

突出显示朗读文本(在 iPhone 的故事书类型应用程序中)
Highlight Read-Along Text (in a storybook type app for iPhone)(突出显示朗读文本(在 iPhone 的故事书类型应用程序中))...
2024-08-12 移动开发问题
9

Cocos2D + 仅禁用 Retina iPad 图形
Cocos2D + Disabling only Retina iPad Graphics(Cocos2D + 仅禁用 Retina iPad 图形)...
2024-08-12 移动开发问题
10

如何将 32 位 PNG 转换为 RGB565?
How to convert 32 bit PNG to RGB565?(如何将 32 位 PNG 转换为 RGB565?)...
2024-08-12 移动开发问题
21