0
我在运行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?
此外,我试图使用@Required +添加setter为test1,但我得到了同样的错误。
你知道会发生什么吗?
感谢
从ORID
你不需要定义'testDao' bean。 Spring将使用'@ ContextConfiguration'配置将'DaoImpl'注入'testDao'。只需从Spring上下文配置中删除测试类bean –
是的,这就是解决方案!感谢Orid! – Lombric