1

Roblectric's FragmentController allowed us to drive the lifecycle of the Fragment to a desired state. It seems that FragmentScenario always takes the Fragment under test to its resumed state. One would assume that calling moveToState(CREATED) would take the Fragment back to through its onCreate(), but in reality, as per the docs, moveToState() simulates an external app interacting with the Fragment under test. This means that moveToState(CREATED) moves the Fragment under test through onPause() and onStop() as it would happen when a new Activity is launched.

To drive the fragment to a different lifecycle state, call moveToState(). This methods supports the following states as arguments: CREATED, STARTED, RESUMED, and DESTROYED. This action simulates a situation where the activity containing your fragment changes its state because it's interrupted by another app or a system action.

Is it possible to somehow direct FragmentScenario to drive the Fragment to a desired state instead of always going through onResume()? How do we test that something happened inside onCreate() and not inside onResume() using FragmentScenario? Am I missing something here?

Emmanuel
  • 13,083
  • 4
  • 39
  • 53

1 Answers1

0

Not sure why you need to test something during fragment's onCreate, but I had the case to supply my fragment with fake viewmodel(mocking happy case, etc.) - you can do it as follows:

@Test fun yetAnotherTest(){

    val fakeViewModel = YourViewModel(fakeDependency1, fakeDependency2,...)

    val scenario: FragmentScenario<YourFragment> =
        launchFragmentInContainer {
            YourFragment().apply {
                viewModel = fakeViewModel
            }
        }
}

and some minor modifications

lateinit var viewmodel: YourViewModel

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    //if this is yetAnotherTest() run, line is skipped 
    if (!::viewModel.isInitialized) {
        //normal setup
        viewModel = provideYourViewModel()
    }

alternatively, you can provide FragmentFactory for your fragment so you can test fragments with FragmentScenario more easily.

Lukas
  • 1,216
  • 12
  • 25
  • This requires modifying production code to accommodate tests and you still wouldn't know when the view model was interacted with. I found a solution that doesn't require that, but after having a [`discussion`](https://github.com/android/android-test/issues/593) with someone from the Android test team, it seems this "limitation" is intentional. – Emmanuel Mar 21 '20 at 14:58