测试服务类中的错误

时间:2012-03-13 08:56:14

标签: android unit-testing junit

java.lang.NullPointerException
at com.android.deviceintelligence1.test.Testappdata.testappd(Testappdata.java:29)
at java.lang.reflect.Method.invokeNative(Native Method)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:169)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:154)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:529)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1448)

运行我的测试类后出现错误。错误日志。

public class Testappdata extends ServiceTestCase<MainService> {

    public Testappdata() {
        super(MainService.class);
    }

    protected void setUp() throws Exception {
        try {
            super.setUp();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }
    MainService main;

    public void testappd() {
        main = getService();
        String Package = "com.android";
        Assert.assertNotNull(main.appData(Package));

    }

这是我的测试类。测试服务以获取数据值。

public class MainService extends Service {
private final static String TAG = "Device Intelligence";
double lat = 0.0;
double lng = 0.0;
List<Address> addresses = null;
String addre;
Handler mHandler = new Handler();
String lPackAgeName, packAgeName = "";
public static DataHelper dh;

public String appData(String pName) {
    PackageManager pm = getPackageManager();
    try {

        Method getPackageSizeInfo = pm.getClass().getMethod(
                "getPackageSizeInfo", String.class,
                IPackageStatsObserver.class);
        getPackageSizeInfo.invoke(pm, pName,
                new IPackageStatsObserver.Stub() {
                    public void onGetStatsCompleted(PackageStats pStats,
                            boolean succeeded) throws RemoteException {
                        data_value = String.valueOf(pStats.dataSize / 1024)
                                + "kb";
                        Log.d("bugs", "datavalue: " + data_value);
                    }
                });
    } catch (Exception e) {
        e.printStackTrace();
    }
    return data_value;
}

这是我的服务类。所以如何清除我的错误。在测试类中需要进行任何更改以摆脱错误。请提前获取帮助。

1 个答案:

答案 0 :(得分:2)

我认为NullPointerException来自这一行:

... ...

public void testappd() {
  main = getService(); // <-- Wrong at here, this will not return a testable service
  String Package = "com.android";
  Assert.assertNotNull(main.appData(Package)); // <-- throw NullPointerException
}

... ...

获取可测试服务的正确方法是在ServiceTestCase类中调用startService(Intent)或bindService(Intent),查看API here

  

测试用例等待调用onCreate(),直到你的一个测试方法调用startService(Intent)或bindService(Intent)。这使您有机会在测试正在运行的服务之前设置或调整任何其他框架或测试逻辑。

假设你有一个正确的启动服务,你应该写下这样的测试代码:

startService(new Intent(getContext(), MainService.class));
main = getService();
... ...

希望这有帮助。