![](/img/trans.png)
[英]How do I inject dependencies in Junit test case using Guice before @Rule runs?
[英]Inject string into class using Guice for JUnit test
我有一種情況需要測試一個函數,但是類已經注入了String值,如下所示:
public class SomeClass{
@Inject
@Named("api")
private String api;
public Observable<String> get(String uuidData){
//do something with "api" variable
}
}
現在我如何從我的JUnit測試用例中注入這個? 我也在使用Mockito,但它不允許我模仿原始類型。
看起來這里有兩個選項:
選項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,也可以測試該類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.