ius*_*ser 0 testing spring constructor annotations mocking
我有一个类似下面的课程
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(){
....
}
Run Code Online (Sandbox Code Playgroud)
那么我该如何为此编写测试呢?当我正在读取属性文件中的值时,在我尝试调用构造函数时进行测试,因为用户名和密码为null,我得到一个空指针异常,测试失败.有什么办法可以解决这个问题并成功测试吗?如何在调用构造函数之前设置这些带注释的值?
就像Spring注入的所有东西一样:在单元测试中自己注入它们:
public class Abcd{
private String username;
private String password;
public Abcd(@Value("${username}") userName, @Value("${password}") String password) {
...
}
...
}
Run Code Online (Sandbox Code Playgroud)
在你的单元测试中:
Abcd abcd = new Abcd("someUserName", "somePassword");
Run Code Online (Sandbox Code Playgroud)
请记住,依赖注入的主要目标是能够在单元测试中手动注入伪造或模拟依赖项.
归档时间: |
|
查看次数: |
945 次 |
最近记录: |