使用Espresso进行意图存根时出现错误

10

我有两个应用程序通过意图相互交互。我想验证一下,比如说应用程序A正确地调用了startActivity,启动了应用程序B而不是实际地启动它。我已经尝试过各种组合的intending和Espresso,但仍然会通过意图启动应用程序B而不是只是将其存根。这会导致剩余的测试失败,因为应用程序B阻塞了用户界面。有任何想法吗?

@RunWith( AndroidJUnit4.class )
@LargeTest
public class MyActivityUiIntentsTest
{

    @Rule
    public IntentsTestRule<MyActivity> activityRule =
            new IntentsTestRule<>( MyActivity.class, true, false );

    @Test
    public void shouldStartOtherActivityWhenButtonClicked ()
    {
        Intents.init();
        intending( toPackage( "my.package" ) )
            .respondWith( new ActivityResult( Activity.RESULT_OK, null ) );

        activityRule.launchActivity( new Intent() );

        onView( withId( R.id.viewId ) ).perform( click() );
        intended( hasComponent( hasShortClassName( "the.other.class.name" ) ) );

        Intents.release();
    }
}

更新:onClick的代码:

@OnClick( R.id.viewId )
public void startOtherActivity ()
{
   Intent intent = new Intent();
   intent.setClassName( "my.package", "the.other.class.name" );
   startActivity( intent );
   finish();
}

1
我们能看到在onClick中创建Intent的代码吗?你是否已经记录了意图中的包名?也就是说,你的意图并没有捕获正确的意图。 - Blundell
添加了onClick的示例代码。 - brwngrldev
你正在运行哪个设备/模拟器API版本? - Nick Korostelev
这很奇怪。我还以为 IntentsTestRule 会自动处理 initrelease - Blundell
2个回答

4

把你的intending...代码移到launchActivity下面,并删除.init(),因为在启动活动后,IntentsTestRule将为您调用init函数


3
其中之一的解决方案是为意图分派提供间接性。
例如,我们有一个 IntentDispatcher,通过使用自定义 instrumentation 测试运行器技巧,在功能 UI 测试中替换为测试实现。 IntentDispatcher 的真实实现只调用 context.startActivity(),而在测试中,我们打开一个特殊的活动,显示 Intent 的所有内容,以便我们能够使用 Espresso 匹配器验证它是否是我们想要处理的 Intent
此外,我们编写了一堆规则来处理诸如打开相机应用程序和模拟结果或仅模拟常规的 startActivity() 调用等事项。

嘿,Artem和Annyce..你们能推荐一些关于模拟意图和额外信息的材料吗?在2018年有没有最新的测试库更好的推荐?谢谢。 - Ewoks

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接