使用 AndroidX Fragments 的 Robolectric

7

如何使用 Robolectric 测试 AndroidX 片段?

我添加了 testImplementation "org.robolectric:shadows-supportv4:4.0-alpha-3" 依赖项,并尝试使用以下代码:

val controller = SupportFragmentController.setupFragment(
            TestableFragment.buildFragment(DATA),
            TestableFragmentHolderActivity::class.java)

TestableFragmentandroidx.fragment.app.Fragment,而 TestableFragmentHolderActivityandroidx.appcompat.app.AppCompatActivity

但是在测试期间出现了错误:

java.lang.NoSuchMethodError: org.robolectric.shadows.support.v4.SupportFragmentController.setupFragment(Landroidx/fragment/app/Fragment;Ljava/lang/Class;)Landroidx/fragment/app/Fragment;


Robolectric目前不支持AndroidX。 - UKoehler
2个回答

6

使用Robolectric的最新API,有一种新的测试片段的方法。请查看官方文档。您需要创建一个FragmentScenario

val fragmentScenario = launchFragmentInContainer<MyFragment>()

然后像使用Espresso一样进行测试

onView(withId(R.id.text)).check(matches(withText("Hello World!")))

1
不确定它是否是Robolectric API,但据我所了解,它是用于本地单元测试碎片的新API。 - Ufkoku
1
@ufkoku Android团队和Robolectric团队将两个API合并为一个,基本上他们采用了Espresso API并删除了大量的Robolectric特定调用。它仍然在Robolectric之上工作,但看起来像Espresso。 - fo2rist
1
我们把这些测试放在哪里:在 test 目录还是 androidTest 目录?? - IgorGanapolsky
这是test文件夹,请参见示例https://github.com/robolectric/robolectric-samples 据我所知,使用gradle在设备和本地JVM上启动相同的测试尚不受支持(仅使用Google自己的内部Bazel解决方案)。 - fo2rist
这如何允许在片段中指定父活动? - IgorGanapolsky

1

它还在 beta 阶段吗? - IgorGanapolsky
Robolectric 4已经发布 http://robolectric.org/blog/2018/10/25/robolectric-4-0/ - fo2rist

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接