I have a class which looks like the below
public class Abcd{
private @Value("${username}")
String username;
private @Value("${password}")
String password;
public Abcd(){
ServiceService serv = new ServiceService();
Service port = serv.getServicePort();
BindingProvider bp = (BindingProvider) port;
bp.getRequestContext().put(BindingProvider.USERNAME_PROPERTY, username);
bp.getRequestContext().put(BindingProvider.PASSWORD_PROPERTY, password);
}
public void getSomeValueMethod(){
....
}
So how do I write a test for this? As I’m reading the values from the properties file, while testing when I try to call the constructor, as the username and password are null I get a null pointer exception and the test fails. Is there any way I can overcome this problem and test it successfully? How can I set those annotated values before calling the constructor?
Just like everything injected by Spring: by injecting them yourself in the unit test:
And in your unit test:
Remember that dependency injection’s main goal is to be able to manually inject fake or mock dependencies in unit tests.