Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
599 views
in Technique[技术] by (71.8m points)

testing - How to test a class which has properties being set using spring @values annotation?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Just like everything injected by Spring: by injecting them yourself in the unit test:

public class Abcd{

    private String username;
    private String password;

    public Abcd(@Value("${username}") userName, @Value("${password}") String password) {
        ...
    }
    ...
}

And in your unit test:

Abcd abcd = new Abcd("someUserName", "somePassword");

Remember that dependency injection's main goal is to be able to manually inject fake or mock dependencies in unit tests.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...