首页 > 解决方案 > 使用 android Dagger 2 和 Robolectric 进行单元测试

问题描述

我正在用 androiddagger2和进行单元测试roboletric,但我注入的对象是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);

}

配置模块

@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);
    }

}

这是我的代码,希望你能给我一些帮助。也许我以错误的方式使用了该设备?

标签: androidunit-testingdagger-2robolectric

解决方案


推荐阅读