如何从Robolectric上的服务中获取一个结果代码。

问题描述 投票:0回答:1

我正在测试一个服务。这个想法很平常:一个活动调用服务,给它一个待定的意图,服务把一个意图连同额外的数据和resultCode发回给活动,如下所示。

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

我可以通过调用来获取额外的数据 shadowService.peekNextStartedActivity()但结果代码呢?我如何以及从哪里可以检索到它?

    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.

先谢谢你。

android unit-testing robolectric
1个回答
0
投票

好吧,Robolectric的影子系统工作得很好。

我添加了一个新的影子类。

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

Voilà.

© www.soinside.com 2019 - 2024. All rights reserved.