我正在尝试编写一些单元测试,以断言我的应用程序中的不同版本的Android SDK使用了适当的密码套件。
Build.VERSION.SDK_INT
我正在尝试使用
Field.set()
呼叫
我有一个实用方法,看起来像这样(从
https://stackoverflow.com/a/40303593/1226095
private static void mockSdkVersion(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);
}
然后我有几个测试利用了这一点:
@Test
public void testApprovedCipherListForApi16() throws Exception {
// force SDK_INT to 16
mockSdkVersion(Build.VERSION.class.getField("SDK_INT"), 16);
// obtain the list of suites that should be returned for API 16
ArrayList<String> approvedCipherSuites = ConnectionSpec.APPROVED_CIPHER_SUITES;
// assert things...
}
@Test
public void testApprovedCipherListForApi20() throws Exception {
// force SDK_INT to 20
mockSdkVersion(Build.VERSION.class.getField("SDK_INT"), 20);
// obtain the list of suites that should be returned for API 20
ArrayList<String> approvedCipherSuites = ConnectionSpec.APPROVED_CIPHER_SUITES;
// assert things...
}
当我一次运行一个测试时,这是可行的,但当我一次运行所有测试时(例如使用像Jenkins这样的CI设置),似乎没有重置值(它保持在16),这是因为它是静态的。
有什么想法吗
a) 我怎么才能避开这个?
b) 我怎么能嘲笑这个呢?