是. Dagger2适用于单元测试和仪器化测试.这里有一个例子:
https://github.com/googlesamples/android-architecture/tree/todo-mvp-dagger
以下是模拟变体中使用的模块示例,可用于单元/ ui测试:
@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());
}
}