gpt4 book ai didi

安卓 Espresso : How do I test a specific Fragment when following one activity to several fragment architecture

转载 作者:IT王子 更新时间:2023-10-28 23:33:09 24 4
gpt4 key购买 nike

我的应用由一个 Activity 组成,用于许多 Fragments

我希望使用 Espresso 来测试 Fragments 的 UI。但是我遇到了一个问题。

如何测试未添加到 onCreate 中的 ActivityFragment。我看到的所有 Fragment 示例都涉及在 onCreate 中添加的 Fragment。那么如何告诉 Espresso 转到特定的 Fragment 并从那里开始?

谢谢

最佳答案

如果您使用的是导航架构组件,您可以在测试开始时通过深度链接到目标 fragment (使用适当的参数)立即测试每个 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]

destinationId 是导航图中的 fragment 目标 ID。这是一个在您准备好启动 fragment 后将执行的调用示例:

launchFragment(R.id.target_fragment, targetBundle())

private fun targetBundle(): Bundle? {
val bundle = Bundle()
bundle.putString(ARGUMENT_ID, "Argument needed by fragment")
return bundle
}

这里也有更详细的回答:https://stackoverflow.com/a/55203154/2125351

关于安卓 Espresso : How do I test a specific Fragment when following one activity to several fragment architecture,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38376153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com