2017-07-11 91 views

回答

2

如果您使用的是ActivityTestRule,那么这样的事情呢?

Intents.init(); 
Intent intent = // Build your intent 

rule.launchActivity(intent); 

// Assertions  

Intents.release() 

我并不是一个真正的咖啡的用户,但我假设将启动活动,并onNewIntent()将被调用。然后做出你的断言。

注意:这是使用专为此目的设计的Espresso Intent库。
androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.2'

+0

谢谢,它工作正常,但显示我的错误:无法在45秒内启动意向意图。也许主线程在合理的时间内没有闲置? –

+0

Espresso Intents旨在处理被测应用程序发送** out **的意图。这里没有必要使用它。你可以在[intro](https://developer.android.com/training/testing/espresso/intents.html)中阅读它 –

1

方法onNewIntent()是公共的,所以你实际上可以直接调用它:

activityTestRule.getActivity().onNewIntent(new Intent()) 

这实际工作,而是因为你在呼唤从测试应用程序线程的方法,它不是太好。如果调用onNewIntent()将导致UI上的任何更改,您将得到一个异常,因为只有创建视图的线程才能更改它。为了解决这个问题,您可以强制UI线程

activityTestRule.getActivity().runOnUiThread(() -> { 
    activityTestRule.getActivity().onNewIntent(new Intent())); 
}); 

上运行这将允许您测试活动的onNewIntent()方法。

顺便说一句,你说的是你的问题,你还想检查一下被定义为singleTop的行为。而不是直接调用该方法,你就可以开始实际应在活动引发onNewIntent()下测试的活动:

Intent intent = new Intent(activityTestRule.getActivity().getApplicationContext(), ActivityUnderTest.class); 
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 

InstrumentationRegistry.getTargetContext().startActivity(intent)); 

这应该结束了通话活动的onNewIntent()下测试,只要它被定义为singleTop,否则它会启动一个新的活动实例。

相关问题