【发布时间】:2015-08-31 11:58:42
【问题描述】:
我想为 DAO 编写一个 Junit 测试。该项目本身工作。所有类和方法都有效。测试的所有数据正确。为什么不好?
例外是 --- 无法自动装配字段:private com.epam.edu.jtc.dao.CoursesDAOImpl com.epam.edu.jtc.test.CourseTest.coursesDao;嵌套异常是 org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type of [com.epam.edu.jtc.dao.CoursesDAOImpl] found for dependency: 预期至少有 1 个 bean 有资格作为此依赖项的自动装配候选者。依赖注解:{@org.springframework.beans.factory.annotation.Autowired(required=true)}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-context.xml" })
public class CourseTest
{
@Autowired
private CoursesDAOImpl coursesDao;
@Test
public void testFindCourseById()
{
Course course = coursesDao.findCourseById(322);
Assert.assertEquals("Python", course.getName());
Assert.assertEquals("Development Manager", course.getCategory());
Assert.assertEquals("python.com", course.getLinks());
return;
}
}
测试上下文.xml
<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"
xmlns:security="http://www.springframework.org/schema/security"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
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-3.2.xsd">
<!-- the test application context definition for the jdbc based tests -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close"
p:driverClassName="org.h2.Driver"
p:url="jdbc:h2:tcp://localhost:9092/~/QWE;INIT=create schema if not exists QWE\;"
p:username="sa"
p:password=""
/>
CoursesDAO.java
public interface CoursesDAO {
public Course findCourseById(Integer key);
}
课程DAOImpl.java
@Repository
public class CoursesDAOImpl implements CoursesDAO {
@Autowired
private SessionFactory sessionFactory;
public Course findCourseById(Integer id) {
Session session = sessionFactory.getCurrentSession();
session.beginTransaction();
Course course = (Course) session.get(Course.class, id);
session.getTransaction().commit();
return course;
}
【问题讨论】:
-
您的测试上下文似乎没有启用组件的自动扫描。
-
-
添加了
和 .. 都一样有这样的异常 -
添加了
和
标签: java spring testing junit dao