【问题标题】:Set resource annotated field of a class in unit tests在单元测试中设置类的资源注释字段
【发布时间】:2013-04-10 13:47:05
【问题描述】:

我有课。

public class Definitions{
@Resource(name="schemas")
private Collection<String> schemas;
}

这个类是通过spring初始化的。 弹簧文件:test.xml

<util:list id="schemas">
    <value>"A"</value>
    <value>"b"</value>
</util:list



<bean id="Definitions" />

有什么方法可以在不使用 spring 的情况下在单元测试中将值插入私有字段模式(用资源注释)。我尝试通过反射使用设置私有变量,但这也没有帮助(可能是由于安全限制)。

即使使用弹簧, ApplicationContext context = new ClassPathXmlApplicationContext("test.xml"); 它无法在定义 bean 中加载模式。访问架构时出现“NullPointerException”。

【问题讨论】:

    标签: spring


    【解决方案1】:

    为其添加一个设置器:

    public class Definitions{
        private Collection<String> schemas;
    
        @Resource(name="schemas")
        public void setSchemas(Collection<String> schemas) {
            this.schemas = schemas;
        }
    }
    

    这是依赖注入的原理:在单元测试中手动注入依赖,通过构造函数或 setter 注入。

    【讨论】:

      【解决方案2】:

      尝试执行以下操作:

      在你的 spring.xml 中插入列表:

      <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:util="http://www.springframework.org/schema/util" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
          <util:list id="listTest">
              <value>Valor 1</value>
              <value>Valor 2</value>
          </util:list>
      </beans>
      

      在您的代码中引用该列表:

      @Resource(name = "listTest")
      private List<String> listTest;
      

      我在这里测试过,它在 Spring 4 和 Spring 3 上运行良好,不需要实现 setter 方法。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2017-05-22
        • 1970-01-01
        • 2014-08-21
        • 2017-03-19
        • 2013-03-22
        • 2017-05-20
        • 2019-03-24
        相关资源
        最近更新 更多