How to test Fragment with Fragment Scenario?

Viewed 4839

I am trying to test a Fragment in isolation. To do this, I am trying FragmentScenario.

Android Documentation offers a really good example here. But My test always fails because my fragment cast the activity to an interface at onAttach.

FragmentScenario luanches a container Activity which (obviously) does not implement the interface required by my fragment.

My question is how to get around this? How to I force the container activity to implement the interface I need? or Is there a better way of doing this? Maybe remove the casting on onAttach and replace with with a different method?

2 Answers

I took a different approach. I ended up using ActivityScenario for the fragments that had callbacks to the Activity.

Created an AccountTestActivity in my Development build. The activity implements all of my various callbacks (LoginCallback, CreateAccountCallback, etc..) from the fragments that I wanted to test.

I don't want to open my classes for testing or add extra functions.

scenario = ActivityScenario.launch(AccountTestActivity::class.java).onActivity {
        logInFragment = LogInFragment()
        it.startFragment(logInFragment)
    }

Use a hook to assign the member, extend the fragment, override the hook to provide a mock of that interface. If not, use a DI to inject that into a public member and just assign a mock directly.

class MainFragment : Fragment {

   override fun onAttach(context:Context) {
       mViewInterface = provideViewInterface()
   }

   protected fun provideViewInterface() = activity
}

class TestMainFragment:MainFragment() {
   override fun provideViewInterface() = mock()
}
Related