它看起來像有兩個選項:
選項1:設置注射JUnit測試
//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的@Before
:重構你的類使用的構造注射劑
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的情況下進行測試。