Android 如何从Robolectric上的服务发送resultCode

Android 如何从Robolectric上的服务发送resultCode,android,unit-testing,robolectric,Android,Unit Testing,Robolectric,我正在测试一个服务。这种想法很常见:活动调用服务并给出一个挂起的意图,服务将意图连同额外数据和结果代码一起发送回活动,如下所示: Intent intent = new Intent().putExtra(TheService.SOME_REPLY, reason); pi.send(service, TheService.SOME_RESULT, intent); 我可以通过调用shadowService.peek nextstartedactivity()来检索额外的代码,

我正在测试一个服务。这种想法很常见:活动调用服务并给出一个挂起的意图,服务将意图连同额外数据和结果代码一起发送回活动,如下所示:

    Intent intent = new Intent().putExtra(TheService.SOME_REPLY, reason);
    pi.send(service, TheService.SOME_RESULT, intent);
我可以通过调用
shadowService.peek nextstartedactivity()
来检索额外的代码,但是结果代码呢?如何从何处检索

    Intent intent = new Intent(ApplicationProvider.getApplicationContext(), TheService.class)
            .setAction(action)
            .putExtra(TheService.EXTRA_PI, pi);

    service.onHandleIntent(intent);

    ShadowService shadowService = Shadows.shadowOf(service);
    Intent intent2 = shadowService.peekNextStartedActivity();
    assertNotNull(error, intent.getExtras());
    Object reply = intent.getExtras().getParcelable(TheService.SOME_REPLY);
    assertNotNull(reply);
    assertTrue(reply instanceof SomeReply);
    // ... etc.

提前感谢。

好吧,机器人阴影系统工作起来很有魅力

我添加了一个新的shadow类:

@Implements(PendingIntent.class)
public class ShadowPendingIntent extends org.robolectric.shadows.ShadowPendingIntent {
    private int code;

    public int getCode() {
        return code;
    }

    @Override
    @Implementation
    protected void send(Context context, int code, Intent intent, PendingIntent.OnFinished onFinished, Handler handler, String requiredPermission, Bundle options) throws PendingIntent.CanceledException {
        this.code = code;
        super.send(context, this.code, intent, onFinished, handler, requiredPermission, options);
    }
}
然后在带有注释的测试中使用它:

@RunWith(RobolectricTestRunner.class)
@Config(shadows = {ShadowPendingIntent.class})
public class TestXxx {
最后在测试中检查:

    ShadowPendingIntent spi = (ShadowPendingIntent) Shadows.shadowOf(pi);
    assertEquals(TheService.SOME_REPLY, spi.getCode());