Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test Fragment with Fragment Scenario?

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?

like image 895
Archie G. Quiñones Avatar asked Dec 17 '18 07:12

Archie G. Quiñones


People also ask

How do you pass data between two fragments?

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.

How do you associate a fragment with an activity?

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.


1 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)
    }
like image 76
zabson Avatar answered Oct 06 '22 00:10

zabson