Home > front end >  IllegalStateException when a getString() is called inside a Fragment Class when Unit Testing with Ro
IllegalStateException when a getString() is called inside a Fragment Class when Unit Testing with Ro

Time:09-17

I am getting IllegalStateException when a getString() is called inside a Fragment 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 Code

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

Test Code

@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()
}

CodePudding user response:

I think the problem might be fragmentTransaction.commit() because commit is asynchronous so when someTest() starts, the commit might have ended or not. The documentation says:

The commit does not happen immediately

Replacing commit for commitNow or commitNowAllowingStateLoss should fix the problem. From the same documentation quoted above, the commit method:

Commits this transaction synchronously

  • Related