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?
Share data between a parent and child fragment When working with child fragments, your parent fragment and its child fragments might need to share data with each other. To share data between these fragments, use the parent fragment as the ViewModel scope.
Add a fragment to an activity You can add your fragment to the activity's view hierarchy either by defining the fragment in your activity's layout file or by defining a fragment container in your activity's layout file and then programmatically adding the fragment from within your activity.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With