我用Dagger2在我的Android应用程序。基本上,我注入了的HttpClient
(接口) MainActivity
。
I use Dagger2 in my android app.
Basically I inject a HttpClient
(interface) in MainActivity
.
@Module
public class MainActivityModule{
@Provides public HttpClient providesHttpComponent(){
return new RealHttpClient();
}
}
@Component( modules = MainActivityModule.class )
public interface MainActivityComponent {
public MainActivity injectActivity(MainActivity);
}
public class MainActivity extends Activity {
public void onCreate(Bundle saved){
super.onCreate();
injectDependencies();
}
protected void injectDependencies(){
Dagger_MainActivityComponent
.builder()
.mainActivityComponent( new MainActivityModule())
.build()
.injectActivity(this);
}
}
到目前为止好,那就像预期。现在我想写一些单元测试(而不是Android的仪器测试)为 MainActivity
在这里我想用 TestMainActivityModule
而不是 MainActivityModule
。
So far so good, that works like expected. Now I want to write some unit tests (not android instrumentation tests) for MainActivity
where I want to use TestMainActivityModule
instead of MainActivityModule
.
@Module (overrides = true )
public class TestMainActivtiyModule extends MainActivityModule {
@Provides public HttpClient(){
return new MockHttpClient();
}
}
我的问题是:如何强制 MainActivity
使用 TestMainActivitiyModule
而不是 MainActivityModule的
?是否有一个良好的解决方案是什么?
My question is: How do I force MainActivity
to use TestMainActivitiyModule
instead of MainActivityModule
? Is there a good solution for that?
我目前的做法是用继承和重写 getModule()
,像这样
My current approach is to use inheritance and to override getModule()
, something like this
public class TestMainActivity extend MainActivity {
@Override
protected void injectDependencies(){
Dagger_MainActivityComponent
.builder()
.mainActivityComponent( new TestMainActivtiyModule())
.build()
.injectActivity(this);
}
}
和运行对 TestMainActivity
单元测试,而不是 MainActivity
。
and to run unit test against TestMainActivity
instead of MainActivity
.
我想它的工作原理,但我面对这种方法的问题之一是,我无法启动 TestMainActivity
与意图
,因为我不能在的AndroidManifest.xml
I guess it works, but one of the problems I'm facing with this approach is that I can't start TestMainActivity
with an Intent
because I can't specify it in AndroidManifest.xml
有谁知道单元测试与dagger2一个更好的方法在Android?
Does anyone know a better approach for unit testing with dagger2 on android?
我已经使用了参与维持两个模块(一个用于应用程序,一个用于测试)并行构建变种(前开始的方法:应用
和整合
)。仍然不知道如何解决好尺度所以因人而异。我会很高兴地看到一个更好的解决方案!
The approach I've started using has involved maintaining two modules (one for the app, one for testing) in parallel build variants (ex: app
and integration
). Still not sure how well that solution scales so YMMV. I'd be very happy to see a better solution!
这也是一个伟大的阅读:的http://engineering.circle.com/instrumentation-testing-with-dagger-mockito-and-es$p$psso/
This is also a great read: http://engineering.circle.com/instrumentation-testing-with-dagger-mockito-and-espresso/