如何使用robolectric来测试额外数据的启动意图

Fre*_*ind 18 testing android android-intent robolectric

在一个活动中,我用一些随机的额外数据开始了一个新的Intent:

Intent newIntent = new Intent(this, UserActivity.class);
newIntent.putExtra("key", generateRandomKey());
startActivity(newIntent);
Run Code Online (Sandbox Code Playgroud)

我测试了这样:

Intent intent = new Intent(myactivity, UserActivity.class);
Assert.assertThat(activity, new StartedMatcher(intent));
Run Code Online (Sandbox Code Playgroud)

它失败了,因为intent在我的测试代码中没有额外的数据key.

由于key是随机的,因此很难提供相同的密钥.所以我只想测试一下intent的目标类UserActivity,但是没有办法做到这一点.

有解决方案吗?

Pau*_*bra 25

如果将generateRandomKey()方法提取到一个单独的类中,则可以将(该方法是手动或使用类似RoboGuice之类的东西)注入到测试中,以便在Robolectric运行时生成的"随机"键实际上是已知值.但在生产代码中仍然是随机的.

然后,您可以捕获活动创建的意图,并测试"key"是否包含预期的测试值.


但是,直接回答你的问题......

当我测试是否生成了意图(在这种情况下是通过按钮单击)并指向我使用的正确目标

public static void assertButtonClickLaunchesActivity(Activity activity, Button btn, String targetActivityName) {
    btn.performClick();
    ShadowActivity shadowActivity = shadowOf(activity);
    Intent startedIntent = shadowActivity.getNextStartedActivity();
    ShadowIntent shadowIntent = shadowOf(startedIntent);
    assertThat(shadowIntent.getComponent().getClassName(), equalTo(targetActivityName));
}
Run Code Online (Sandbox Code Playgroud)