Robolectric:使用LocationManager的组件抛出NPE

时间:2015-07-26 11:25:29

标签: java android nullpointerexception robolectric locationmanager

我正在使用Robolectric测试一个服务,该服务在其onCreate()方法中获取对LocationManager的引用,并在之后立即请求位置更新:

public void onCreate() {
    super.onCreate();

    // Other code...

    lm = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    lm.requestSingleUpdate(LocationManager.GPS_PROVIDER, this, null);

    // Other code...
}

问题是,NullPointerException会引发requestSingleUpdate()。我的测试注释如下:

@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, emulateSdk = 19,
    manifest = "src/main/AndroidManifest.xml")

请注意,即使在服务之外,也会发生这样的简单单元测试:

@Test
public void test() {
    Application app = RuntimeEnvironment.application;
    LocationManager lm = (LocationManager) app.getSystemService(LOCATION_SERVICE);
    lm.requestSingleUpdate(...);
}

问题出在哪里?有没有其他方法来测试使用像LocationManager这样的系统服务的组件?

1 个答案:

答案 0 :(得分:0)

我认为你需要通过ShadowLocationManager来模拟它。

相关问题