首页 > 解决方案 > 如何对 Android Studio 上的活动是否已更改进行单元测试

问题描述

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

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

标签: androidunit-testingandroid-studio

解决方案


您可以使用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类参考,了解更多关于你可以做什么断言意图被触发。

希望有帮助!


推荐阅读