PowerMock testing - set static field of class

后端 未结 6 1990
孤独总比滥情好
孤独总比滥情好 2020-12-08 00:30

I\'m having difficulty finding a way to set a static field of a class. It\'s basically like this:

public class Foo{
    // ...
    private static B b = null;         


        
6条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-08 00:49

    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 unless setAccessible(true) has succeeded for this field and this field is non-static, 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".

提交回复
热议问题