I have a situation where I need to test a function but the class has injected String value like this:
public class SomeClass{
@Inject
@Named("api")
private String api;
public Observable<String> get(String uuidData){
//do something with "api" variable
}
}
Now how do I inject this from my JUnit test case? I am also using Mockito but it's not allowing me to mock primitive types.
It looks like there are two options here:
Option 1: Set up injection in the @Before
of your JUnit test
//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);
}
Option 2: Refactor your class to use constructor injection
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
}
}
Now your @Before
method will look like this:
//test doubles
String testDoubleApi;
//system under test
SomeClass someClass;
@Before
public void setUp() throws Exception {
String testDoubleApi = "testDouble";
someClass = new SomeClass(testDoubleApi);
}
Out of the two options, I would say the second is preferable. You can see it leads to much less boiler-plate and the class can be tested even without Guice.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With