Using reflection to change static final File.separatorChar for unit testing?

前端 未结 7 889
太阳男子
太阳男子 2020-11-28 09:37

Specifically, I\'m trying to create a unit test for a method which requires uses File.separatorChar to build paths on windows and unix. The code must run on bot

7条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-28 09:43

    here I am going to set value for "android.os.Build.VERSION.RELEASE", where VERSION is the class name and RELEASE is the final static string value.

    If the underlying field is final, the method throws an IllegalAccessException so that we need to use setAccessible(true) , NoSuchFieldException needs to be added when you use field.set() method

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({Build.VERSION.class})
    public class RuntimePermissionUtilsTest {
    @Test
    public void hasStoragePermissions() throws IllegalAccessException, NoSuchFieldException {
        Field field = Build.VERSION.class.getField("RELEASE");
        field.setAccessible(true);
        field.set(null,"Marshmallow");
     }
    }
    

    now the value of String RELEASE will return "Marshmallow".

提交回复
热议问题