简体   繁体   中英

Espresso test with Dagger2 injection

I want to inject my components that are created by dagger in my Espresso tests.

The components should be the same, so, that are no necessity of overriding anything from dagger.

I have the following class:

@RunWith(AndroidJUnit4.class)
public class AccountRepositoryTest {
    @Inject
    AccountRepository repository;

    @Before
    public void setUp() throws Exception {
        new DaggerTestComponent().builder().build().inject(this);
    }
}

Since I can't add AccountRepositoryTest to my main DaggerComponent class, I created another component class in my androidTests folder:

@Singleton
@Component(modules = arrayOf(AppModule::class, DatabaseModule::class, RepositoryModule::class))
interface TestComponent: AppComponent {
     fun inject(accountRepositoryTest: AccountRepositoryTest)
}

But dagger never generates the ComponentClass from TestComponent interface, when I compile the code, I always receive this error:

Error:(26, 7) error: cannot find symbol class DaggerTestComponent

If I comment the line, my code compiles, so I'm sure that it is just this that is preventing dagger from generating the class.

So my question is: how do make dagger generate a component class from an interface defined in androidTests folder?

The solution was to add dagger-compiler to androidTest dependencies.

If you are using kotlin:

kaptAndroidTest "com.google.dagger:dagger-compiler:$daggerVersion"

If you are using java:

androidTestAnnotationProcessor "com.google.dagger:dagger-compiler:$daggerVersion"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM