首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >测试包中的Android测试新服务

测试包中的Android测试新服务
EN

Stack Overflow用户
提问于 2018-01-11 07:42:28
回答 2查看 1.1K关注 0票数 12

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

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

代码语言:javascript
复制
@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是在“测试”包中真正创建的。如果我试图通过应用程序上下文启动TestService,它会给我一个错误,说是Unable to start service Intent { cmp=com.example.abc.test/com.example.abc.WakefulIntentSenderTest$TestService } U=0: not found error。

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

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

我真正想测试的是com.example.abc背后的一个类,它使用PowerManager通过Wakelock启动服务。但这是我现在的想法,因为我甚至不能从Test包启动服务。

不幸的是,在主包中包含TestService对我来说也不是一个选择:(

EN

回答 2

Stack Overflow用户

发布于 2018-01-17 20:58:15

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

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

票数 4
EN

Stack Overflow用户

发布于 2019-03-03 22:57:17

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48197850

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档