I have a simple Fragment
like so:
class SomeFragment : DaggerFragment() {
...
}
Now I want to test this Fragment
using FragmentScenario
class LoginFragmentTest {
@Test
fun test() {
launchFragmentInContainer<SomeFragment>()
onView(withId(R.id.someButton))
.check(matches(isDisplayed()))
}
}
But everytime I try to the test its always:
java.lang.IllegalArgumentException: No injector was found for <...SomeFragment>
How can I properly run the test? Can anybody help me here?
I found two ways to solve the problem:
typealias
,DaggerFragment
and special test variants of your fragmentsI consider the first approach cleaner and would recommend to use it rather than the latter, but I'll describe both of them, so you can make your own choice.
Build flavors with
typealias
mock
andprod
:app/build.gradle
typealias
depending on the flavor, let's call itBaseFragment
:prod
flavor,app/src/prod/com.example.mypackage/BaseFragment.kt
mock
flavor,app/src/mock/com.example.mypackage/BaseFragment.kt
BaseFragment
alias in your fragments:FragmentScenario
switch from theprod*
build variant to themock*
one and set all the dependencies that are supposed to be injected somewhere in your test class (e.g. using mocks)Own
DaggerFragment
and test variants of the fragmentsDaggerFragment
(based on the actualdagger.android.support.DaggerFragment
implementation):DaggerFragment
implementation and set the fragmentopen
:injectMembers
method:TestSomeFragment
in your tests.