java.lang.NullPointerException: 无法为 null ShadowPreferenceManager 获取阴影



有人可以帮助我了解如何解决此异常吗?

我引用了 Robolectric 测试在 shadowOf 上失败,但我已经在使用 this 来访问SharedPreferences,即

SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);

@Config(emulateSdk = 18)
@RunWith(RobolectricTestRunner.class)
public class SomeClassTest {
    private Context context;
    private SomeClassTest someClassTest;
    private SharedPreferences sharedPreferences;
    @Before
    public void setup() throws Exception {
        context = mock(Context.class);
        sharedPreferences = ShadowPreferenceManager.getDefaultSharedPreferences(context);
        someClassTest = new SomeClassTest(context);
    }
    @Test
    public void someClassProduction() {
        when(someClassTest.getEnvironment()).thenReturn("PRODUCTION");
        when(someClassTest.getBaseUrl()).thenReturn("https://www.someUrl.com/v1/");
        assertTrue(someclassTest.getTestUrl().equals("https://www.someurl.com/v1/counts.json")
    }
}
java.lang.NullPointerException: can't get a shadow for null
    at org.robolectric.bytecode.ShadowWrangler.shadowOf(ShadowWrangler.java:442)
    at org.robolectric.Robolectric.shadowOf_(Robolectric.java:1059)
    at org.robolectric.Robolectric.shadowOf(Robolectric.java:477)
    at org.robolectric.shadows.ShadowPreferenceManager.getDefaultSharedPreferences(ShadowPreferenceManager.java:21)
    at android.preference.PreferenceManager.getDefaultSharedPreferences(PreferenceManager.java)

事实证明,我不得不用context = Robolectric.application替换context = mock(Context.class)

以下是更新的测试:

@Config(emulateSdk = 18)
@RunWith(RobolectricTestRunner.class)
public class SomeClassTest {
    private Context context;
    private SomeClassTest someClassTest;
    private SharedPreferences sharedPreferences;
    @Before
    public void setup() throws Exception {
        context = Roboelectric.application;
        sharedPreferences = ShadowPreferenceManager.getDefaultSharedPreferences(context);
        someClassTest = new SomeClassTest(context);
    }
    @Test
    public void someClassProduction() {
        when(someClassTest.getEnvironment()).thenReturn("PRODUCTION");
        when(someClassTest.getBaseUrl()).thenReturn("https://www.someUrl.com/v1/");
        assertTrue(someclassTest.getTestUrl().equals("https://www.someurl.com/v1/counts.json")
    }
}

相关内容

  • 没有找到相关文章

最新更新