Android:编写片段测试用例 [英] Android: Writing test cases for Fragments
问题描述
在我以前的项目中,我通过活动完成了大部分工作,并根据文档使用了ActivityInstrumentationTestCase2:
http://developer.android.com/tools/testing/activity_testing.html
我有一个如何使用活动测试用例的想法;但是当涉及到Fragment时,我没有太多的主意,也没有找到很多与此相关的文档.
那么,当我有几个片段具有一个或两个活动时,如何编写测试用例呢?
任何示例代码或示例都将更有帮助.
In my previous projects I've done most of the work through Activities and used ActivityInstrumentationTestCase2 as per the document:
http://developer.android.com/tools/testing/activity_testing.html
I have an idea how to work with Activity Test cases; but when it comes to Fragment ,I don't have much idea nor found much documents related to that.
So how to write test cases when I have several fragments with one or two actvities?
Any example code or sample would be more helpful.
推荐答案
AndroidX
提供了一个库FragmentScenario
,用于创建片段并更改其状态.
AndroidX
provides a library, FragmentScenario
, to create fragments and change their state.
app/build.gradle
dependencies {
def fragment_version = "1.0.0"
// ...
debugImplementation 'androidx.fragment:fragment-testing:$fragment_version'
}
示例
@RunWith(AndroidJUnit4::class)
class MyTestSuite {
@Test fun testEventFragment() {
// The "fragmentArgs" and "factory" arguments are optional.
val fragmentArgs = Bundle().apply {
putInt("selectedListItem", 0)
}
val factory = MyFragmentFactory()
val scenario = launchFragmentInContainer<MyFragment>(
fragmentArgs, factory)
onView(withId(R.id.text)).check(matches(withText("Hello World!")))
}
}
有关官方文档的更多信息.
这篇关于Android:编写片段测试用例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!