android - 使用 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包括ConfigModule
和ServiceModule
@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);
}
}
这是我的代码,希望你能给我一些帮助。也许我以错误的方式使用了该设备?
解决方案
推荐阅读
- javascript - 有没有办法将用户脚本注入移动网页并在重新加载后保留?
- javascript - MongooseServerSelectionError:连接 ECONNREFUSED 127.0.0.1:27017
- java - 如何解决错误:无法初始化主类选择。ClustererExecution
- php - 如何将预加载标签添加到 wordpress 中的页面英雄图像?
- python - TensorFlow 版本(2.1.0 和 2.4.0)之间的准确率和损失显着降低
- testing - 使用 GitLab CI/CD 的 E2E 测试自动化工作流程
- mysql - 需要指导以增加我们项目的请求流量
- javascript - 在javascript中传递对象
- java - Android Activity:在 onCreate() 之后处理 Intent?
- java - Java Selenium 测试失败