https://developer.android.com/studio/test/index.html
Are you able to use Dagger2 for Local unit tests
(Located at module-name/src/test/java/.), Instrumented tests
(Located at module-name/src/androidTest/java/.) or both?
Are there any examples of this?
Yes. Dagger2
works in unit tests and instrumented tests. An example is here: https://github.com/googlesamples/android-architecture/tree/todo-mvp-dagger
Here is an example of a module used in a mock variant which can be used for unit/ui testing:
@Module
abstract public class TasksRepositoryModule {
private static final int THREAD_COUNT = 3;
@Singleton
@Binds
@Local
abstract TasksDataSource provideTasksLocalDataSource(TasksLocalDataSource dataSource);
@Singleton
@Binds
@Remote
abstract TasksDataSource provideTasksRemoteDataSource(FakeTasksRemoteDataSource dataSource);
@Singleton
@Provides
static ToDoDatabase provideDb(Application context) {
return Room.databaseBuilder(context.getApplicationContext(), ToDoDatabase.class, "Tasks.db")
.build();
}
@Singleton
@Provides
static TasksDao provideTasksDao(ToDoDatabase db) {
return db.taskDao();
}
@Singleton
@Provides
static AppExecutors provideAppExecutors() {
return new AppExecutors(new DiskIOThreadExecutor(),
Executors.newFixedThreadPool(THREAD_COUNT),
new AppExecutors.MainThreadExecutor());
}
}
https://github.com/googlesamples/android-architecture/blob/todo-mvp-dagger/todoapp/app/src/mock/java/com/example/android/architecture/blueprints/todoapp/data/source/TasksRepositoryModule.java#L24
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