代码之家  ›  专栏  ›  技术社区  ›  jesses.co.tt

领域Java中静态类的set()

  •  0
  • jesses.co.tt  · 技术社区  · 7 年前

    我正在尝试编写一些单元测试,以断言我的应用程序中的不同版本的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) 我怎么能嘲笑这个呢?

    2 回复  |  直到 7 年前
        1
  •  1
  •   tsolakp    7 年前

    您需要重置生成。每次测试方法调用后的版本。类似这样:

    private static final int DEFAULT_VERION = Build.VERSION.SDK_INT;
    
    @After
    public void after(){
        mockSdkVersion( Build.VERSION.class.getField("SDK_INT"), DEFAULT_VERION );
    }
    
        2
  •  0
  •   jesses.co.tt    7 年前

    @Config(sdk = Build.VERSION_CODES.XXX) 测试方法注释(假设您使用的是RoboElectric

    http://robolectric.org/configuring/