Android在测试包中测试新服务

Dil*_*lon 12 java junit android android-testing android-instrumentation

我想在框架中测试一个类,该框架基于intent启动不同的服务.但是,我有问题,创建TestService内部的androidTest/连接时,Android的测试正在运行.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);
    }
}
Run Code Online (Sandbox Code Playgroud)

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

以上代码实际上只是为了证明我是否可以启动服务.

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

我真正想要测试的是一个com.example.abc使用a PowerManager来启动服务的类Wakelock.但是现在我已经想到了,因为我甚至无法从Test包启动服务.

不幸的是,在主包内有TestService也不是我的选择:(