Evgeniy Mishustin Evgeniy Mishustin - 5 months ago 64
Android Question

Stub value of Build.VERSION.SDK_INT in Local Unit Test

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
}


How can I cover all the code ?

I mean I want to run two tests with different SDK_INT to enter both blocks.

Is it possible in android local unit tests using
Mockito
/
PowerMockito
?

Thanks

Answer

Can you try changing the value using reflexion.

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

And then something like

 setFinalStatic(Build.VERSION.class.getField("SDK_INT"), 123);

I haven't tested it, so it might not work as intended.