I want to write a Junit test to the DAO. The project work itself. All classes and methods work. All data from the test correctly. Why is it bad?
Exception is --- Could not autowire field: private com.epam.edu.jtc.dao.CoursesDAOImpl com.epam.edu.jtc.test.CourseTest.coursesDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.epam.edu.jtc.dao.CoursesDAOImpl] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@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=""
/>
CoursesDAO.java
public interface CoursesDAO {
public Course findCourseById(Integer key);
}
CoursesDAOImpl.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;
}
You should autowire the interface, instead of the implementation class, like so:
Hope it helps.