Android Espresso:将一项活动跟踪到多个片段架构后,如何测试特定的片段 [英] Android Espresso: How do I test a specific Fragment when following one activity to several fragment architecture
问题描述
我的应用包含一个Activity
代表许多Fragments
.
My app consists of one Activity
for many Fragments
.
我希望使用Espresso来测试Fragments
的UI.但是我遇到了一个问题.
I wish to use Espresso to test the UI of the Fragments
. However I ran into a problem.
如何测试未添加到onCreate
中Activity
的Fragment
.我在Fragments
中看到的所有示例都涉及到onCreate
中添加的Fragment
.
那么我如何告诉Espresso转到特定的Fragment
并从那里开始?
How can I test a Fragment
which is not added to an Activity
in onCreate
. All examples I have seen with Fragments
involve the Fragment
being added in onCreate
.
So how can I tell Espresso to go to a specific Fragment
and start from there?
谢谢
推荐答案
Espresso仅在显示Fragments
时才能测试.这就要求它们必须用Activity
显示.
Espresso can test Fragments
only if they are displayed. And that requires them to be displayed by an Activity
.
在当前设置下,您必须使用Espresso来(如用户一样)使用click()
到您实际要测试的Fragment
.
With your current setup you'll have to use Espresso to click()
your way (like a user would) to the Fragment
you actually want to test.
在我的一个项目中,我有一个显示Fragments
的ViewPager
.对于那些Fragments
,我使用自定义的FragmentTestRule
对其进行隔离测试.我可以直接启动每个Fragment
并使用Espresso对其进行测试.参见此答案.
In one of my projects I have a ViewPager
that displays Fragments
. For those Fragments
I use a custom FragmentTestRule
to test them in isolation. I can start each Fragment
directly and use Espresso to test it. See this answer.
您还可以:
- 请勿使用
Fragments
.Activities
更易于测试.您可以单独测试每个Activity
.在大多数情况下,Fragments
没有提供优于Activities
的优势.Fragments
只是使实施和测试更加困难. - 使
FragmentActivity
在创建时直接显示特定的Fragment
.例如.通过为FragmentActivity
提供额外的特殊意图.但这会在您的应用中添加测试代码,这通常不是一个好的解决方案.
- Do not use
Fragments
.Activities
are easier to test. You can test eachActivity
on its own. In most casesFragments
offer no advantage overActivities
.Fragments
just make the implementation and testing more difficult. - Enable your
FragmentActivity
to directly show a certainFragment
when it is created. E.g. by supplying a special intent extra to yourFragmentActivity
. But this would add testing code to your app, which is generally not a good solution.
这篇关于Android Espresso:将一项活动跟踪到多个片段架构后,如何测试特定的片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!