如何测试使用spring @values批注设置了属性的类? [英] How to test a class which has properties being set using spring @values annotation?

查看:92
本文介绍了如何测试使用spring @values批注设置了属性的类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像下面的课

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(){
....
}

那我该如何为此编写测试?当我从属性文件中读取值时,在尝试调用构造函数时进行测试时,由于用户名和密码为null,因此出现了null指针异常,并且测试失败.有什么办法可以克服这个问题并成功进行测试?在调用构造函数之前,如何设置这些带注释的值?

推荐答案

就像Spring注入的所有东西一样:通过将它们自己注入到单元测试中:

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) {
        ...
    }
    ...
}

在您的单元测试中:

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.

这篇关于如何测试使用spring @values批注设置了属性的类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆