Min*_*aze 3 java junit dependency-injection guice
我有一种情况需要测试一个函数,但是类已经注入了String值,如下所示:
public class SomeClass{
@Inject
@Named("api")
private String api;
public Observable<String> get(String uuidData){
//do something with "api" variable
}
}
Run Code Online (Sandbox Code Playgroud)
现在我如何从我的JUnit测试用例中注入这个?我也在使用Mockito,但它不允许我模仿原始类型.
看起来这里有两个选项:
选项1:在@BeforeJUnit测试中设置注入
//test doubles
String testDoubleApi;
//system under test
SomeClass someClass;
@Before
public void setUp() throws Exception {
String testDoubleApi = "testDouble";
Injector injector = Guice.createInjector(new Module() {
@Override
protected void configure(Binder binder) {
binder.bind(String.class).annotatedWith(Names.named("api")).toInstance(testDouble);
}
});
injector.inject(someClass);
}
Run Code Online (Sandbox Code Playgroud)
选项2:重构您的类以使用构造函数注入
public class SomeClass{
private String api;
@Inject
SomeClass(@Named("api") String api) {
this.api = api;
}
public Observable<String> get(String uuidData){
//do something with "api" variable
}
}
Run Code Online (Sandbox Code Playgroud)
现在你的@Before方法将如下所示:
//test doubles
String testDoubleApi;
//system under test
SomeClass someClass;
@Before
public void setUp() throws Exception {
String testDoubleApi = "testDouble";
someClass = new SomeClass(testDoubleApi);
}
Run Code Online (Sandbox Code Playgroud)
在这两个选项中,我会说第二个更好.您可以看到它导致更少的锅炉板,即使没有Guice,也可以测试该类.
| 归档时间: |
|
| 查看次数: |
2022 次 |
| 最近记录: |