如何对Android Studio上的活动是否进行更改进行单元测试

时间:2018-11-11 00:17:04

标签: android unit-testing android-studio

我想测试将我重定向到另一个活动的方法“ OnClick”是否有效。但是我不知道如何在单元测试中做到这一点。

public void onClickManageServiceButton(View view){ 
    Intent intent = new Intent(getApplicationContext(), ServiceManagement.class);
    startActivity(intent);

2 个答案:

答案 0 :(得分:0)

您应该使用Robolectric进行测试。

在Robolectric的gradle中添加testImplementation http://robolectric.org/getting-started/

return getManager().transaction(async (entityManger) => {
    const firstReady = await entityManger
      .createQueryBuilder(Ready, 'ready')
      .setLock('pessimistic_write')
      .select()
      .orderBy('timestamp')
      .where('locked = false or exp < :now', { now: Date.now() })
      .getOne();
    if (!firstReady) return;
    await entityManger
      .createQueryBuilder(Ready, 'ready')
      .update()
      .set({ locked: true, exp: Date.now() + vars.PG.LOCK_EXP })
      .where('provider = :provider', { provider: firstReady.provider })
      .execute();
    logger.debug(`Acquired lock on ${firstReady.provider} and S3 object key ${firstReady.key}`);
    return firstReady.key;
  });

其中ACTUAL_ACTIVITY是您具有onClickManageServiceButton方法的活动。

技巧:活动类中的“按CMD + SHIFT + T”,您将快速采取行动为该活动创建测试

答案 1 :(得分:0)

您可以使用Espresson Intents API轻松做到这一点:

在测试中,设置一个IntentsTestRule,该规则将记录被触发的意图。

@Rule public IntentsTestRule<MyActivity> intentsTestRule =
    new IntentsTestRule<>(MyActivity.class);

在测试中,启动活动,触发被测方法,然后断言:

@Test
public void onClickManageServiceButton() {
    // By default the rule launch your activity, so it's running by the time test starts

    // Assuming the method to test is on your activity under test...
    // You many need to find a View or mock one out to pass to the method.
    mIntentsTestRule.getActivity().onClickManageServiceButton(null);

    // Espresso will have recorded the intent being fired - now use the intents
    // API to assert that the expected intent was launched...
    Intents.intended(hasComponent(ServiceManagement.class.getName()));
}

检查IntentsIntentMatchers类引用,以获取有关您可以执行的更多断言意图的信息。

希望有帮助!