无法在 InstrumentedTest 中测试外部服务绑定 Android

Unable to test external service binding Android in InstrumentedTest

我正在尝试测试对我定义的服务的外部绑定。在 class 我用于仪器测试之后:

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

@Test
public void testWithBoundService() throws TimeoutException, RemoteException {
    IMyInterface iMyInterface;
    Intent serviceIntent =
            new Intent(ApplicationProvider.getApplicationContext(),
                    MyService.class);
    IBinder binder = serviceRule.bindService(serviceIntent);
    assertNotNull(binder);
    iMyInterface = IMyInterface.Stub.asInterface(binder);
    assertTrue(iMyInterface.retrieveValue(new Attribute()).getValues().get(0).equals("home"));
}

@Test
public void testWithBoundServiceExternal() throws TimeoutException, RemoteException {
    IMyInterface iMyInterface;
    Intent serviceIntent = new Intent();
    serviceIntent.setClassName("a.b.c.d", "a.b.c.d.MyService");
    IBinder binder = serviceRule.bindService(serviceIntent);
    assertNotNull(binder);
    iMyInterface = IMyInterface.Stub.asInterface(binder);
    boolean reachedHere = false;

    assertTrue(iMyInterface.retrieveValue(new Attribute()).getValues().get(0).equals("home"));

}

第一个测试函数运行没有任何错误,第二个失败并显示以下消息:

Failed to bind to service! Is your service declared in the manifest?

Service定义在包a.b.c.d中,与Aidl接口相同,而instrumentedTest在a.b.c.e包

中运行

几分钟后我意识到 Manifest 有一个不同的包,并且,为了调用该服务,您应该使用 Manifest 的包。所以假设你在标签中有一个属性 package="a.b.c.f",为了调用你应该使用的外部服务:

serviceIntent.setClassName("a.b.c.f", "a.b.c.d.MyService")