我想给DAO写一个Junit测试。项目本身。所有类和方法都有效。测试中的所有数据正确无误。为什么不好?

例外是---无法自动连线字段:private com.epam.edu.jtc.dao.CoursesDAOImpl com.epam.edu.jtc.test.CourseTest.coursesDao;嵌套的异常是org.springframework.beans.factory.NoSuchBeanDefinitionException:未找到类型为[com.epam.edu.jtc.dao.CoursesDAOImpl]的合格Bean作为依赖项:至少应有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;
}
}


test-context.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=""
     />


课程DAO.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;
   }

最佳答案

您应该自动连接接口,而不是实现类,如下所示:

@Autowired
private CoursesDAO coursesDao;


希望能帮助到你。

09-18 21:46