Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java EE (J2EE) и Spring > написание junit теста для Hibernate Spring


Автор: cryo 2.3.2011, 18:42
Здравствуйте есть проблема при запуске теста выдается ошибка. Я использую MySQL. Хочу проверить получение данных из БД посредством Hibernate

Вот мой ТЕСТ:
Код

package net.mine.employeemanager.dao;

import static org.junit.Assert.*;
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.AbstractTransactionalJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;

import org.hibernate.SessionFactory;
import org.hibernate.Session;
import net.mine.employeemanager.domain.Division;


@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:/WEB-INF/spring/data.xml," +
                                   "classpath*:/WEB-INF/spring/root-context.xml," +
                                   "classpath*:/WEB-INF/spring/security.xml," +
                                   "classpath*:/WEB-INF/spring/appServlet/servlet-context.xml," +
                                   "classpath*:/WEB-INF/spring/appServlet/controllers.xml," +
                                   "classpath*:/hibernate.cfg.xml"})
@TransactionConfiguration(defaultRollback=true)
@Transactional
public class EmployeeDAOImplTest extends AbstractTransactionalJUnit4SpringContextTests {
    @Autowired
    private SessionFactory sessionFactory;
    @Test
    public void testListDivsion(){
        
        
        Session session = sessionFactory.getCurrentSession();

        Division division = new Division();
        division.setId(51);
        division.setNAME("Testtesttest");
        
        session.save(division);
        
          session.flush();
          assertNotNull(division.getId()); 

    }
}


Вот класс, который я тестирую

Код

package net.mine.employeemanager.dao;
import java.util.List;

import net.mine.employeemanager.domain.Division;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

@Repository
public class EmployeeDAOImpl implements EmployeeDAO {

    @Autowired
    private SessionFactory sessionFactory;
        
         @SuppressWarnings("unchecked")
    public List<Division> listDivision() {

        
return sessionFactory.getCurrentSession().createQuery("from Division ").list();
    }


Вот мой Division.class

Код

package net.mine.employeemanager.domain;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.OneToMany;

import org.apache.commons.lang.WordUtils;

@Entity
@Table(name = "division")

public class Division {

    @Id
    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;
    
    @Column(name = "NAME")
    private String name;
        
         @OneToMany(mappedBy = "division")
         public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }
         
          public String getNAME() {
        return name;
    }

    public void setNAME(String name) {
        
        this.name = WordUtils.capitalizeFully(name);
         }

}


Мой data.xml
Код

<?xml  version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:aop="http://www.springframework.org/schema/aop"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:jee="http://www.springframework.org/schema/jee"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="http://www.springframework.org/schema/beans 
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
        http://www.springframework.org/schema/aop 
        http://www.springframework.org/schema/aop/spring-aop.xsd
        http://www.springframework.org/schema/jee 
        http://www.springframework.org/schema/jee/spring-jee.xsd
        http://www.springframework.org/schema/lang 
        http://www.springframework.org/schema/lang/spring-lang.xsd
        http://www.springframework.org/schema/tx 
        http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/util 
        http://www.springframework.org/schema/util/spring-util.xsd">

    <!-- Настраивает управление транзакциями с помощью аннотации @Transactional -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />
    </bean>

    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basename" value="classpath:messages" />
        <property name="defaultEncoding" value="UTF-8" />
    </bean>





    <bean id="propertyConfigurer"
        class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
        p:location="/WEB-INF/jdbc.properties" />

    
    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        p:driverClassName="${jdbc.driverClassName}" 
        p:url="${jdbc.databaseurl}"
        p:username="${jdbc.username}" 
        p:password="${jdbc.password}" />

    
    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="configLocation">
            <value>classpath:hibernate.cfg.xml</value>
        </property>
        <property name="configurationClass">
            <value>org.hibernate.cfg.AnnotationConfiguration</value>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.show_sql">true</prop>
                <prop key="hibernate.dialect">${jdbc.dialect}</prop>
                <prop key="hibernate.connection.charSet">UTF-8</prop>
            </props>
        </property>
    </bean>
    
        
<!-- freemarker config -->
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
  <property name="templateLoaderPath" value="/WEB-INF/freemarker/"/>
   <property name="freemarkerSettings">
            <props>
                <prop key="default_encoding">UTF-8</prop>
            </props>
        </property>
        
</bean>

<!--View resolvers can also be configured with ResourceBundles or XML files. If you need
  different view resolving based on Locale, you have to use the resource bundle resolver.-->
<bean id="viewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
  <property name="cache" value="true"/>
  <property name="prefix" value=""/>
  <property name="suffix" value=".ftl"/>
  <property name="contentType">
            <value>text/html;charset=UTF-8</value>
        </property>
</bean>    
<!-- /freemarker config-->



</beans>

Вот Ошибка:
Код

RROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@e51b2c] to prepare test instance [net.mine.employeemanager.dao.EmployeeDAOImplTest@15aed57]
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'net.mine.employeemanager.dao.EmployeeDAOImplTest': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests.setDataSource(javax.sql.DataSource); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
.....
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire method: public void org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests.setDataSource(javax.sql.DataSource); nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
...
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No matching bean of type [javax.sql.DataSource] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {}
...
org.apache.maven.surefire.booter.SurefireExecutionException: org.junit.runner.notification.RunNotifier.testAborted(Lorg/junit/runner/Description;Ljava/lang/Throwable;)V; nested exception is java.lang.NoSuchMethodError: org.junit.runner.notification.RunNotifier.testAborted(Lorg/junit/runner/Description;Ljava/lang/Throwable;)V
java.lang.NoSuchMethodError: org.junit.runner.notification.RunNotifier.testAborted(Lorg/junit/runner/Description;Ljava/lang/Throwable;)V


Помогите,а то запутался куда копать, в интернете куча разных примеров каждый со своими нюансами. Если надо, скину еще информации, настройки и т.д. по проекту.....

Автор: MisterCleric 2.3.2011, 18:53
Привет. В том месте, где ты инжектишь DataSource напиши так:
Код

@Autowired
@Qualifier("dataSource") //here
private DataSource dataSource;


что совпадает с id бина dataSource

Автор: cryo 2.3.2011, 21:03
Боюсь что ничего не изменилось  :(

http://s1.ipicture.ru/Gallery/Viewfull/3804619.html

Автор: cryo 2.3.2011, 22:12
Возможно, не создается бин, потому что не может подгрузиться конфигурационный файл. Но не могу увидеть почему он не считывается.

Автор: cryo 3.3.2011, 16:33
Код

@SuppressWarnings("unchecked")
    public List<Division> listDivision() {
        
return sessionFactory.getCurrentSession().createQuery("from Division ").list();
    }


Как вообще протестировать эту функцию, используя Hibernate(hibernate-core-3.3.2GA), Spring3.0.5, junit4.7
 smile 
Неделю не могу найти ответ.

Автор: Старовъръ 5.3.2011, 00:02
http://static.springsource.org/spring/docs/3.0.x/reference/testing.html

Автор: cryo 5.3.2011, 12:24
Спасибо всем, разобрался. Оказалось лишнее написал. Вплоть до того, что кроме data.xml ничего лишнего не надо было указывать в locations. defaultRollback=true —это мне не понадобилось. Ну и остальных много недочетов/ошибок,  к которым так и чешутся руки придраться или исправить. Например, division.setId(51) — не нужно, так как  
Код


    @Column(name = "ID")
    @GeneratedValue(strategy = GenerationType.AUTO)

— генерируется автоматически.

Добавлено через 7 минут и 15 секунд
+ @Qualifier("sessionFactory")

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)