問題描述
我想知道是否有任何方法來存根 Build.Version.SDK_INT
的值?假設(shè)我在 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);
經(jīng)過測試.有效.
更新:有一種更清潔的方法.
創(chuàng)建接口
interface BuildVersionProvider {
fun currentVersion(): Int
}
實現(xiàn)接口
class BuildVersionProviderImpl : BuildVersionProvider {
override fun currentVersion() = Build.VERSION.SDK_INT
}
只要您需要當(dāng)前的構(gòu)建版本,就可以通過接口將此類作為構(gòu)造函數(shù)參數(shù)注入.然后在測試時創(chuàng)建一個SUT(被測系統(tǒng))對象.您可以自己實現(xiàn)接口.這種處理方式可能需要更多代碼,但遵循 SOLID 原則,并為您提供可測試的代碼,而不會弄亂反射和系統(tǒng)變量.
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.
這篇關(guān)于本地單元測試中 Build.VERSION.SDK_INT 的存根值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!