如何获取从 Robolectric 上的服务发送的结果代码

How to get a resultCode sent from a service on Robolectric

我正在测试一项服务。这个想法很常见:activity 调用服务给它一个未决的意图,服务将一个意图连同额外的数据和 resultCode 发送回 activity,如下所示:

    Intent intent = new Intent().putExtra(TheService.SOME_REPLY, reason);
    pi.send(service, TheService.SOME_RESULT, intent);

我可以通过调用 shadowService.peekNextStartedActivity() 来检索额外的内容,但是 resultCode 呢?如何以及从何处检索它?

    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.

提前致谢。

嗯,Robolectric 影子系统很有魅力。

我添加了一个新的影子class:

@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());

瞧。