【问题标题】:Unit Test Service using Junit 4使用 Junit 4 的单元测试服务
【发布时间】:2015-12-16 13:08:16
【问题描述】:

我正在尝试使用 JUNIT4 为 Android 服务编写单元测试。 按照我的服务代码:

class myService extends Service {

    // Binder given to clients
    private IBinder mBinder = null;

    @Override
    public void onCreate() {
        super.onCreate();
        mBinder = new LocalBinder();
    }

    public int multiply(int x, int y){
        return (x*y);

    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    public class LocalBinder extends Binder {

        public myService getService() {
            // Return this instance of LocalService so clients can call     public methods.
            return myService.this;
        }
    }
}

还有我的单元测试代码:

public class testServiceUlt {

@Rule
public final ServiceTestRule mServiceRule = new ServiceTestRule();

@Test
public void testWithBoundService() throws TimeoutException, InterruptedException {

    // Create the service Intent.
    Intent serviceIntent =
            new Intent(InstrumentationRegistry.getTargetContext(), myService.class);

    // Bind the service and grab a reference to the binder.
    IBinder binder = mServiceRule.bindService(serviceIntent);

    // Get the reference to the service, or you can call public methods on the binder directly.
    myService service = ((myService.LocalBinder) binder).getService();

    int val = service.multiply(80, 0);
    assertEquals("should be zero", 0, val);

    }

}

问题是活页夹是空的,我收到以下错误: java.lang.NullPointerException:尝试在空对象引用上调用虚拟方法 'com.example.xxx.xxx.xxx com.example.xxx.xxx.xxx$LocalBinder.getService()'

你能告诉我我的问题是什么吗? P.S - 我知道如何将 Junit3 与 ServiceTestCase 一起使用,但我想使用 Junit4

谢谢, 扎奇

【问题讨论】:

    标签: android unit-testing junit4


    【解决方案1】:

    我设法解决了这个问题。 错误地我的 AndroidManifest.xml 文件没有包含服务。

    【讨论】:

      【解决方案2】:

      在我的情况下,问题是我在 androidTest Manifest 文件中声明了该服务,但由于任何原因都无法正常工作。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-09
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2013-06-30
        • 1970-01-01
        相关资源
        最近更新 更多