其实很简单。在测试活动时,我有一个包含以下内容的基础测试类:
@Rule @JvmField
val activityRule: IntentsTestRule<*>
@Rule @JvmField
val chain: RuleChain
init {
activityRule = IntentsTestRule(
activityClass,
true, // true if the Activity should be placed into "touch mode" when started
false) // launchActivity
var initChain = RuleChain.outerRule(firstRule)
.around(OkHttpIdlingResourceRule())
.around(activityRule)
for (rule in additionalTestRules) {
initChain = initChain.around(rule)
}
chain = initChain
}
在测试中,Activity 是使用 activityRule.launchActivity(null) 启动的,现在在测试 Fragments 时,它变成:
@Rule
@JvmField
val chain: RuleChain
init {
var initChain = RuleChain.outerRule(firstRule)
.around(OkHttpIdlingResourceRule())
for (rule in additionalTestRules) {
initChain = initChain.around(rule)
}
chain = initChain
}
在测试中,使用 launchFragmentInContainer() 启动 Fragment