我正在使用Android dagger2
和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 包括ConfigModule
和ServiceModule
@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);
}
}
这是我的代码,希望您能给我一些帮助。 也许我用错了单位?