使用spring运行junit测试时出错。
这是我的测试类:
package testdao;
import static org.junit.Assert.assertTrue;
import java.net.UnknownHostException;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import dao.daoImpl.DaoImpl;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:TestDao-context.xml")
public class TestDao {
@Autowired
private DaoImpl test1;
@Test
public void test() {
try {
test1.connect();
assertTrue(true);
} catch (UnknownHostException e) {
e.printStackTrace();
assertTrue(false);
}
}
}
然后是我的xml配置文件:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Uncomment and add your base-package here: <context:component-scan base-package="org.springframework.samples.service"/> -->
<!-- DAO -->
<!-- MongoFactoryBean instance -->
<bean id="mongoFactoryBean" class="org.springframework.data.mongodb.core.MongoFactoryBean">
<property name="host" value="127.0.0.1" />
<property name="port" value="27017" />
</bean>
<bean id="mongoDbFactory"
class="org.springframework.data.mongodb.core.SimpleMongoDbFactory">
<constructor-arg name="mongo" ref="mongoFactoryBean" />
<constructor-arg name="databaseName" value="agence_voyage" />
</bean>
<bean id="dao" class="dao.daoImpl.DaoImpl">
<property name="mongoFactory" ref="mongoDbFactory" />
</bean>
<!-- Services -->
<bean id="service" class="service.serviceImpl.ServiceImpl">
<property name="dao" ref="dao" />
</bean>
<!-- Tests -->
<bean id="testDao" class="testdao.TestDao">
<property name="test1" ref="dao"/>
</bean>
</beans>
所以当我运行它时,我得到一个由以下引起的ApplicationContext加载错误:
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'testDao' defined in class path resource [TestDao-context.xml]: Error setting property values; nested exception is org.springframework.beans.NotWritablePropertyException: Invalid property 'test1' of bean class [testdao.TestDao]: Bean property 'test1' is not writable or has an invalid setter method. Does the parameter type of the setter match the return type of the getter?
另外我试图为test1使用@Required + add setter,但是我得到了同样的错误。
你知道会发生什么吗?
谢谢
答案 0 :(得分:0)
Orid的解决方案: “你不需要定义testDao bean.Spring会使用@ContextConfiguration配置将DaoImpl注入testDao。只需从Spring上下文配置中删除测试类bean”