[英]Dagger Inject different Dependency to IntentService in prod & test
是否有可能通过匕首将不同的对象注入android.app.IntentService中,具体取决于它是测试还是生产?
这主要是将WebRequest类注入服务的代码(简化)。
public class SomeService extends android.app.IntentService {
@Inject
WebReqeust mWebRequest;
public SomeService(String name) {
super(name);
MainApplication.getInstance().inject(this);
}
@Override
protected void onHandleIntent(Intent intent) {
String json = mWebRequest.getHttpString(url);
JSONObject o = new JSONObject(json);
DBHelper.insert(o);
}
}
@Module(injects = { SomeService.class })
public class WebRequestModule {
@Provides
WebRequest provideWebRequest() {
return new WebRequest();
}
}
public class Modules {
public static Object[] list() {
return new Object[] {
new WebRequestModule()
};
}
}
public class MainApplication extends Application {
private ObjectGraph mOjectGraph;
private static MainApplication sInstance;
@Override
public void onCreate() {
sInstance = this;
mOjectGraph = ObjectGraph.create(Modules.list());
}
public void inject(Object dependent) {
mOjectGraph.inject(dependent);
}
public void addToGraph(Object module) {
mOjectGraph.plus(module);
}
}
我想编写一个模拟http响应的测试。 我从一个新的模块开始
@Module(
injects = SomeService.class,
overrides = true
)
final class MockTestModule {
@Provides
WebRequest provideWebRequest() {
WebRequest webRequest = mock(WebRequest.class);
when(webRequest.getJSONObjectResponse(contains("/register/"))).thenReturn(
new JSONObject(FileHelper.loadJSONFromAssets(this.getClass(),
"mock_register.json")));
when(webRequest.getJSONObjectResponse(contains("/register_validate/"))).thenReturn(
new JSONObject(FileHelper.loadJSONFromAssets(this.getClass(),
"mock_register_validate.json")));
return webRequest;
}
}
在测试中,我尝试了以下
public class RegisterTest extends AndroidTestCase {
protected void setUp() throws Exception {
MainApplication.getInstance().addToGraph(new MockTestModule());
super.setUp();
}
public void test_theActuallTest() {
Registration.registerUser("email@email.com"); // this will start the service
wait_hack(); // This makes the test wait for the reposen form the intentservice, works fine
DBHelper.isUserRegisterd("email@email.com"));
}
}
测试成功执行(请记住,代码经过简化,可能无法编译,仅应代表想法)。 但是,它仍然使用“真实的” WebRequest Impl,而不是模拟的。 我在日志,代理以及我们在服务器上看到的...
我使用RoboGuice进行了类似的操作,而且效果很好。 但是以某种方式我无法用匕首完成。 (我目前正在评估DI框架,这是“必须具备”的条件)
plus
方法实际返回新图。 它不会覆盖原始图形。 据说可以完成您想要的事情,您只需执行此操作即可。
public class MainApplication extends Application {
...
// Mostly used for testing
public void addToGraph(Object module) {
mObjectGraph = mOjectGraph.plus(module);
}
}
这将获取原始图形并将其添加到新模块中,然后只需将新图形分配给您的mObjectGraph引用即可。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.