Spring Test / JUnit问题 - 无法加载应用程序上下文

时间:2010-05-19 13:41:07

标签: xml spring dependency-injection junit testing

我第一次使用Spring并且必须做错事。我有一个包含几个Bean实现的项目,现在我正在尝试使用Spring Test和JUnit创建一个测试类。我正在尝试使用Spring Test将自定义bean注入测试类。

这是我的test-applicationContext.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns=".............">
  <bean
    id="MyUuidFactory"
        class="com.myapp.UuidFactory" 
        scope="singleton" >
    <property name="typeIdentifier" value="CLS" />
  </bean>

  <bean id="ThingyImplTest"
        class="com.myapp.ThingyImplTest"
          scope="singleton">
     <property name="uuidFactory">
        <idref local="MyUuidFactory"   />
     </property>
</bean>
</beans>

MyUuidFactory实例的注入与测试类中的以下代码一起:

private UuidFactory uuidFactory;

public void setUuidFactory(UuidFactory uuidFactory) {
    this.uuidFactory = uuidFactory;
}

但是,当我去运行测试时(在Eclipse或命令行中),我得到以下错误(为简洁省略了堆栈跟踪):

Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'MyImplTest' defined in class path resource [test-applicationContext.xml]:
Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: 
Failed to convert property value of type 'java.lang.String' to required type 'com.myapp.UuidFactory' for property 'uuidFactory'; 
nested exception is java.lang.IllegalStateException: 
Cannot convert value of type [java.lang.String] to required type [com.myapp.UuidFactory] for property 'uuidFactory': 
no matching editors or conversion strategy found

有趣的是,Eclipse / Spring XML编辑器显示我错误拼写任何类型或idref的错误。如果我留下bean,但注释掉依赖注入,一切都会工作,直到我在运行测试时得到NullPointerException ...这是有道理的。

1 个答案:

答案 0 :(得分:3)

尝试<ref/>而非<idref/>

“idref元素只是一种防错方式,可以将容器中另一个bean的id传递给<constructor-arg/><property/>元素。”