当使用 Robolectric 进行单元测试时,在 Fragment Class 中调用 getString() 时出现 IllegalStateException

IllegalStateException when a getString() is called inside a Fragment Class when Unit Testing with Robolectric

在 Fragment 中调用 getString() 时出现 IllegalStateException Class

Caused by: java.lang.IllegalStateException: Fragment SomeFragment{1df37025} (29efd1d0-77c1-4293-a0f6-b808c7559cf4)} not attached to a context.
at androidx.fragment.app.Fragment.requireContext(Fragment.java:805)
at androidx.fragment.app.Fragment.getResources(Fragment.java:869)
at androidx.fragment.app.Fragment.getString(Fragment.java:891)

SomeFragment代码

public void someMethod() {
    getString(R.string.some_res)
}

测试代码

@Before
fun setUp() {
    val activity = Robolectric.buildActivity(SomeActivity::class.java).create().get()
    fragment = SomeFragment()
    fragmentManager = activity.supportFragmentManager
    val fragmentTransaction: FragmentTransaction = fragmentManager.beginTransaction()
    fragmentTransaction.add(fragment, null)
    fragmentTransaction.commit()
}

@Test
@Throws(Exception::class)
fun someTest() {
    fragment.someMethod()
}

我认为问题可能出在 fragmentTransaction.commit() 因为 commit 是异步的所以当 someTest() 开始时,提交可能已经结束也可能没有。 documentation 表示:

The commit does not happen immediately

commit 替换为 commitNowcommitNowAllowingStateLoss 应该可以解决问题。从上面引用的相同文档中,commit 方法:

Commits this transaction synchronously