Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can Dagger2 be used for unit tests and instrumented tests?

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?

like image 916
Etienne Lawlor Avatar asked Nov 07 '22 11:11

Etienne Lawlor


1 Answers

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

like image 107
dazza5000 Avatar answered Nov 15 '22 11:11

dazza5000