【问题标题】:Android Test new Service in Test PackageAndroid 测试测试包中的新服务
【发布时间】:2018-06-20 05:44:03
【问题描述】:

我想在一个基于意图启动不同服务的框架中测试一个类。但是,在运行连接的 android 测试时,我在 androidTest/ 内创建 TestService 时遇到问题。 getService 方法返回null

提前感谢您的任何指导和帮助!

@RunWith(AndroidJUnit4.class)
public class WakefulIntentSenderTest {
    private static final String SOME_ACTION = "someAction";

    private static class TestService extends Service {
        private boolean mCalled;

        @Override
        public void onCreate() {
            super.onCreate();
        }

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

        @Override
        public int onStartCommand(final Intent intent, final int flags, final int startId) {
            mCalled = true;
            return 0;
        }

        public boolean wasCalled() {
            return mCalled;
        }

        public class TestServiceBinder extends Binder {

        public TestService getService() {
            return TestService.this;
        }
    }

    @Test
    public void testWithBoundService() throws TimeoutException {
        // Create the service Intent.
        Intent serviceIntent =
                new Intent(InstrumentationRegistry.getTargetContext(), TestService.class);

        InstrumentationRegistry.getTargetContext().startService(intent);

        // 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.
        TestService service = ((TestService.TestServiceBinder) binder).getService();

        // Verify that the service is working correctly.
        assertEquals(service.wasCalled(), true);
    }
}

我还有其他问题,TestService 是在“Test”包中真正创建的。如果我尝试通过应用上下文启动 TestService,它会给我一个错误提示 Unable to start service Intent { cmp=com.example.abc.test/com.example.abc.WakefulIntentSenderTest$TestService } U=0: not found 错误。

上面的代码真的只是为了演示我是否可以启动一个服务。

更多信息... InstrumentationRegistry 在调用getTargetContext() 时将返回com.example.abc,在调用getContext() 时返回com.example.abc.test

我真正想测试的是com.example.abc 后面的一个类,它使用PowerManager 来启动一个带有Wakelock 的服务。但这暂时在我的脑海中,因为我什至无法从测试包启动服务。

不幸的是,在主包中包含 TestService 也不是我的选择:(

【问题讨论】:

标签: java android junit android-testing android-instrumentation


【解决方案1】:

您需要在 TestService#onBind 中返回您的 TestServiceBinder 类的实例

【讨论】:

    【解决方案2】:

    https://developer.android.com/training/testing/integration-testing/service-testing.html

    Android 提供了一种直接获取服务引用的方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      • 1970-01-01
      • 1970-01-01
      • 2017-06-25
      • 2017-10-04
      • 2019-08-25
      相关资源
      最近更新 更多