Moving from FragmentController to FragmentScenario

195 Views Asked by At

I'm using robolectric and am updating my support fragments to androidx fragments. THis means updating tests that use FragmentController<> to the recommended FragmentScenario.

With FragmentController, i could start it, and I could call controller.get() to get the actual fragment and manipulate it directly, making public calls. Is there a way to do this with FragmentScenario, and get direct access to the androidx.Fragment instance?

The reason I want to call a public method directly, is because the Activity that contains the Fragment listents for an Intent, and invokes a method on its contained fragment, and I want to test the associated behavior of this.

1

There are 1 best solutions below

0
On

THe answer is to use FragmentScenario.onFragment(). THis lets you perform an action on the UI thread of the fragment directly, giving you a reference to the fragment.

e.g.

FragmentScenario<MyCustomFragment> controller = FragmentScenario.launch(MyCustomFragment.class);

controller.onFragment(fragment -> {
    fragment.myCustomFragMethod1();
    fragment.myCustomFragMethod2();
}

// assertions here, testing that myCustomFragMethod1() worked.