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