Reputation: 576
Note: I am not using Dagger-Android, just Dagger 2.
When I started writing my app I was injecting the fragment through the AppComponent so my integration test worked.
Then I created a subcomponent called MainComponent which lives in MainActivity. In my fragment I was getting the subcomponent using
((MainActivity) getActivity()).mainComponent.inject(this);
Then in my integration tests I would do
FragmentScenario.launchInContainer(RecipesListFragment.class, null, R.style.AppTheme, null)
which throws an error
EmptyFragmentActivity cannot be cast to ...MainActivity
as FragmentScenario launches the fragment in an EmptyFragmentActivity.
I thought that in order to fix this I could remove the dependency on MainActivity to get the component so I used a FragmentFactory and passed in MainComponent as a parameter. But now the test fails because when I create the FragmentScenario I do not have the MainComponent to pass it in the factory.
So is there a way to launch the scenario and still use the MainComponent subcomponent?
Upvotes: 0
Views: 326
Reputation: 576
Posting what I did in the end to answer Henrique's question. I read a few posts about it but I can't find them now since it was some time ago.
There was no clear answer so I ended up using the dependency on MainActivity to inject since using the FragmentFactory proved too much hassle without many gains.
In the AndroidTest folder I created an empty MainTestActivity that extends MainActivity.
Then in the FragmentTest
ActivityScenario<MainTestActivity> scenario;
@Before
public void setUp() {
scenario = ActivityScenario.launch(MainTestActivity.class).onActivity(activity -> {
MainFragment fragment = new MainFragment();
activity.startActivityFromFragment(fragment, new Intent(activity, MainTestActivity.class), 0);
});
}
Upvotes: 1