Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inject string into class using Guice for JUnit test

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.

like image 416
Minato Namikaze Avatar asked Jan 04 '23 23:01

Minato Namikaze


1 Answers

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.

like image 157
David Rawson Avatar answered Jan 08 '23 22:01

David Rawson