使用Android Dagger 2和Robolectric进行单元测试

时间:2018-12-20 02:05:12

标签: android unit-testing dagger-2 robolectric

我正在使用Android dagger2roboletric进行单元测试,但是我注入的对象是null。这里的代码:

@RunWith(RobolectricTestRunner.class)
public class ExampleUnitTest {

    @Inject
    MemberService memberService;


    @Before
    public void setUp() {
        Application application = RuntimeEnvironment.application;
        DaggerConfigComponent.builder().configModule(new ConfigModule(application))//provide retrofit okhttpclient
                .serviceModule(new ServiceModule())//provide Memberservice
                .build().inject(this);
    }

    @Test
    public void test(){
      //user memberservice, but it is null
    }
}

configComponent 包括ConfigModuleServiceModule

@Singleton
@Component(modules = {ConfigModule.class, ServiceModule.class})
public interface ConfigComponent {

    void inject(Object o);

}

ConfigModule

@Module(includes = {DaoSessionModule.class, ServiceModule.class})
public class ConfigModule {

    private Application application;

    public ConfigModule(Application application) {
        this.application = application;
    }

    @Singleton
    @Provides
    public Application provideApplication() {
        return this.application;
    }
 @Singleton
    @Provides
    public OkHttpClient provideOkHttpClient(Cache cache, HttpLoggingInterceptor loggingInterceptor) {
        OkHttpClient.Builder builder = new OkHttpClient().newBuilder();
        builder.cache(cache);
        if (BuildConfig.DEBUG) {
            builder.connectTimeout(30, TimeUnit.SECONDS);
            builder.readTimeout(30, TimeUnit.SECONDS);
            builder.writeTimeout(30, TimeUnit.SECONDS);
        }
        return builder.build();
    }

    @Singleton
    @Provides
    public Retrofit provideRetrofit(OkHttpClient okHttpClient) {
        return new Retrofit.Builder()
                .baseUrl(BuildConfig.BASE_URL)
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .client(okHttpClient)
                .build();
    }
}

ServiceModule 提供MemberService

@Module
public class ServiceModule {

    @Singleton
    @Provides
    public MemberService provideMemberService(Retrofit retrofit) {
        return retrofit.create(MemberService.class);
    }

}

这是我的代码,希望您能给我一些帮助。 也许我用错了单位?

0 个答案:

没有答案