使用 Espresso 存根 Intent 时出错
Error When Stubbing Intent with Espresso
我有两个通过意图相互交互的应用程序。我想验证 App A 是否正确调用了 App B 的 startActivity
而没有实际启动 App B。我已经尝试了 intending
的各种组合,Espresso 仍然通过意图启动 App B 而不是仅仅将其删除。这会导致剩余的测试失败,因为 UI 被 App 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();
}
一种可能的解决方案是使用间接的意图调度。
例如,我们有 IntentDispatcher
,我们通过 custom instrumentation test runner.
的技巧将其替换为功能性 ui 测试中的测试实现
IntentDispatcher
的实际实现只是调用 context.startActivity()
,而在测试中我们打开显示 Intent
的所有内容的特殊 activity,因此我们能够验证我们想用 Espresso 匹配器处理 Intent
。
我们还编写了一堆规则来处理打开相机应用程序和模拟结果或只是模拟常规 startActivity()
调用等事情。
将您的 intending...
代码移至 launchActivity 下方并删除 .init()
,因为 IntentsTestRule
将在 activity 启动后为您调用 init
我有两个通过意图相互交互的应用程序。我想验证 App A 是否正确调用了 App B 的 startActivity
而没有实际启动 App B。我已经尝试了 intending
的各种组合,Espresso 仍然通过意图启动 App B 而不是仅仅将其删除。这会导致剩余的测试失败,因为 UI 被 App 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();
}
一种可能的解决方案是使用间接的意图调度。
例如,我们有 IntentDispatcher
,我们通过 custom instrumentation test runner.
IntentDispatcher
的实际实现只是调用 context.startActivity()
,而在测试中我们打开显示 Intent
的所有内容的特殊 activity,因此我们能够验证我们想用 Espresso 匹配器处理 Intent
。
我们还编写了一堆规则来处理打开相机应用程序和模拟结果或只是模拟常规 startActivity()
调用等事情。
将您的 intending...
代码移至 launchActivity 下方并删除 .init()
,因为 IntentsTestRule
将在 activity 启动后为您调用 init