Ers*_*man 20 android android-fragments android-testing android-espresso
我的应用程序包含一个Activity用户Fragments.
我希望使用Espresso来测试用户界面Fragments.但是我遇到了一个问题.
如何测试一个Fragment未添加到Activity在onCreate.我见过的所有例子都Fragments涉及到Fragment被添加onCreate.那么我怎么能告诉Espresso去特定的Fragment并从那里开始呢?
谢谢
如果您正在使用导航架构组件,您可以在测试开始时通过深度链接到目标片段(使用适当的参数)来立即测试每个片段。
@Rule
@JvmField
var activityRule = ActivityTestRule(MainActivity::class.java)
protected fun launchFragment(destinationId: Int,
argBundle: Bundle? = null) {
val launchFragmentIntent = buildLaunchFragmentIntent(destinationId, argBundle)
activityRule.launchActivity(launchFragmentIntent)
}
private fun buildLaunchFragmentIntent(destinationId: Int, argBundle: Bundle?): Intent =
NavDeepLinkBuilder(InstrumentationRegistry.getInstrumentation().targetContext)
.setGraph(R.navigation.navigation)
.setComponentName(MainActivity::class.java)
.setDestination(destinationId)
.setArguments(argBundle)
.createTaskStackBuilder().intents[0]
Run Code Online (Sandbox Code Playgroud)
destinationId 是导航图中的片段目的地 ID。这是在您准备好启动片段后将完成的调用示例:
launchFragment(R.id.target_fragment, targetBundle())
private fun targetBundle(): Bundle? {
val bundle = Bundle()
bundle.putString(ARGUMENT_ID, "Argument needed by fragment")
return bundle
}
Run Code Online (Sandbox Code Playgroud)
这里也有更详细的回答:https : //stackoverflow.com/a/55203154/2125351
因此,根据几家公司的模式和推荐做法。您需要为每个视图编写有针对性的密封测试,无论是活动、片段、对话框片段还是自定义视图。
首先,如果您按以下方式使用 gradle,则需要通过 gradle 将以下库导入到您的项目中
debugImplementation 'androidx.fragment:fragment-testing:1.2.0-rc03'
debugImplementation 'androidx.test:core:1.3.0-alpha03'
Run Code Online (Sandbox Code Playgroud)
为了独立于活动测试片段,您可以通过以下方式启动/启动它:
@Test
fun sampleTesting(){
launchFragmentInContainer<YourFragment>()
onView(withId(R.id.sample_view_id)).perform(click())
}
Run Code Online (Sandbox Code Playgroud)
这样,您可以从您的活动中独立测试您的片段,这也是实现密封和有针对性的 ui 测试的推荐方法之一。有关完整详细信息,您可以阅读 android docs 中的片段测试文档
https://developer.android.com/training/basics/fragments/testing
我发现这个带有大量测试示例的存储库非常有用,尽管它非常受限于具有超级简单测试的测试用例的复杂性。虽然它可以作为开始的指南。
https://github.com/android/testing-samples
tha*_*sma -12
Fragments仅当它们显示时,Espresso 才能进行测试。这需要它们通过Activity.
根据您当前的设置,您必须按照click()自己的方式(就像用户一样)使用 Espresso 来进行Fragment您真正想要测试的测试。
在我的一个项目中,我有一个ViewPager显示Fragments. 对于那些Fragments我使用自定义FragmentTestRule来单独测试它们。我可以Fragment直接启动每个并使用 Espresso 来测试它。看到这个答案。
您还可以:
Fragments。Activities更容易测试。您可以Activity单独测试每个。在大多数情况下,Fragments与 相比没有任何优势Activities。Fragments只会让实施和测试变得更加困难。FragmentActivity直接显示某个内容。Fragment例如,通过向您的FragmentActivity. 但这会向您的应用程序添加测试代码,这通常不是一个好的解决方案。| 归档时间: |
|
| 查看次数: |
14380 次 |
| 最近记录: |