我遇到需要测试函数的情况,但是类已经注入了String值,如下所示:
public class SomeClass{
@Inject
@Named("api")
private String api;
public Observable<String> get(String uuidData){
//do something with "api" variable
}
}
现在我如何从我的JUnit测试用例中注入这个?我也在使用Mockito,但它不允许我模仿原始类型。
答案 0 :(得分:5)
看起来这里有两个选项:
选项1:在JUnit测试的@Before
中设置注入
//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);
}
选项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
}
}
现在,您的@Before
方法将如下所示:
//test doubles
String testDoubleApi;
//system under test
SomeClass someClass;
@Before
public void setUp() throws Exception {
String testDoubleApi = "testDouble";
someClass = new SomeClass(testDoubleApi);
}
在两个选项中,我会说第二个更好。你可以看到它导致更少的锅炉板,即使没有Guice,也可以测试这个类。