Stub value for Build.VERSION.SDK_INT in local Unit Test

I am wondering if in any case I need to drown out the value of Build.Version.SDK_INT ? Suppose I have the following lines in 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 this possible in local android local tests using Mockito / PowerMockito ?

thanks

+6
source share
1 answer

Change the value using reflection.

  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

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

It is tested. Works.

+19
source

All Articles