简体   繁体   English

Robolectric:测试应用程序运行时启动哪个Activity

[英]Robolectric: Test which Activity is launched when application is run

I want to write an automated test using robolectric that confirms a given activity is launched when the application is started. 我想使用robolectric编写一个自动化测试,确认在应用程序启动时启动给定的活动。

This will be my "walking skeleton" acceptance test as described in Freeman and Pryce's TDD book. 这将是我在Freeman和Pryce的TDD书中描述的“行走骨架”验收测试。

The test basically confirms that the application's main intent filter is implemented correctly: 测试基本上确认应用程序的主要意图过滤器是否正确实现:

<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />

I know that it's a test that's barely worth doing, but that's the point of the "walking skeleton" test - and is one I think is worth doing. 我知道这是一项几乎不值得做的测试,但这就是“行走骨架”测试的重点 - 而且我觉得这是值得做的。

How could this be done? 怎么可以这样做? The "hello world" test provided by robolectric is this: robolectric提供的“hello world”测试是这样的:

@Before 
public void setup()
{
    this.activity = Robolectric.buildActivity(MainActivity.class).create().get();
}
@Test
public void shouldHaveHappySmiles() throws Exception 
{
    String appName = this.activity.getString(R.string.app_name);
    assertThat(appName, equalTo("MyApp"));
}

The above runs MainActivity and tests a property of it. 上面运行MainActivity并测试它的属性。 Instead, how can I assert that when the app is launched, it actually starts MainActivity ? 相反,我怎么能断言当应用程序启动时,它实际上启动了MainActivity

As for me this test in general doesn't give much value. 至于我,这个测试一般没有多大价值。 But maybe it is important in your case. 但也许这对你的情况很重要。

I would access `AndroidManifest' and check specific 'ActivityData' with 'IntentFilter': 我将访问`AndroidManifest'并使用'IntentFilter'检查特定的'ActivityData':

AndroidManifest appManifest = Robolectric.getShadowApplication().getAppManifest();
ActivityData activityData = appManifest.getActivityData( "<yourpackage>.MainActivity" );
List<IntentFilterData> intentFilters = activityData.getIntentFilters();
IntentFilterData data = intentFilters.get( 0 );

assertThat( data.getActions() ).contains( "android.intent.action.MAIN" );
assertThat( data.getCategories() ).contains( "android.intent.category.LAUNCHER" );

This is just example, pay attention if you have more intent filters 这只是示例,如果您有更多的意图过滤器,请注意

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM