lundi 10 juillet 2017

Field.set() on a Static Class in Java

I am trying to write some Unit Tests to assert that the proper Cipher Suites are used for varying versions of the Android SDK in my app.

In order to mock the result of Build.VERSION.SDK_INT I am attempting to use the Field.set() call...

I have a utility method that looks like this (pulled from http://ift.tt/2sY42QG and linked answers):

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);
}

and then I have several tests that utilize this like so:

@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...
}

This works when I run the tests one at a time, but when I run them all at once (such as with a CI setup like Jenkins) it seems to be not resetting the value, assumingly because it is Static.

Any thoughts on a) how I can get around this ? b) how I can alternatively mock this ?





Aucun commentaire:

Enregistrer un commentaire