Spring - 引发java.lang.IllegalStateException异常 - JUnit

时间:2015-02-08 20:16:26

标签: java spring hibernate junit

我尝试测试一些课程。我是初学者。当我以JUnit运行测试时它会中止。

我试图改变类路径,但它并不成功。

那是代码:

错误日志:

0    [main] INFO  org.springframework.test.context.TestContextManager org.springframework.test.context.TestContextManager -@TestExecutionListeners is not present for class [class test.TestPersonaDAOImpl]: using defaults.
181  [main] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader org.springframework.beans.factory.xml.XmlBeanDefinitionReader -Loading XML bean definitions from URL [file:/home/rugar/Documents/workspace-sts-3.6.2.RELEASE/struts-spring-hibernate/target/test-classes/datasource-test.xml]
378  [main] INFO  org.springframework.beans.factory.xml.XmlBeanDefinitionReader org.springframework.beans.factory.xml.XmlBeanDefinitionReader -Loading XML bean definitions from URL [file:/home/rugar/Documents/workspace-sts-3.6.2.RELEASE/struts-spring-hibernate/target/classes/applicationContext.xml]
523  [main] INFO  org.springframework.context.support.GenericApplicationContext org.springframework.context.support.GenericApplicationContext -Refreshing org.springframework.context.support.GenericApplicationContext@1fa4f2fd: startup date [Sun Feb 08 14:02:25 CST 2015]; root of context hierarchy
671  [main] INFO  org.springframework.beans.factory.support.DefaultListableBeanFactory org.springframework.beans.factory.support.DefaultListableBeanFactory -Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@30f7f56b: defining beans [dataSource,sessionFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
775  [main] INFO  org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseFactory -Creating embedded database 'dataSource'
907  [main] INFO  org.springframework.jdbc.datasource.init.ResourceDatabasePopulator org.springframework.jdbc.datasource.init.ResourceDatabasePopulator -Executing SQL script from class path resource [esquema.sql]
919  [main] INFO  org.springframework.jdbc.datasource.init.ResourceDatabasePopulator org.springframework.jdbc.datasource.init.ResourceDatabasePopulator -Done executing SQL script from class path resource [esquema.sql] in 12 ms.
919  [main] INFO  org.springframework.jdbc.datasource.init.ResourceDatabasePopulator org.springframework.jdbc.datasource.init.ResourceDatabasePopulator -Executing SQL script from class path resource [datos.sql]
921  [main] INFO  org.springframework.jdbc.datasource.init.ResourceDatabasePopulator org.springframework.jdbc.datasource.init.ResourceDatabasePopulator -Done executing SQL script from class path resource [datos.sql] in 2 ms.
1110 [main] INFO  org.hibernate.annotations.common.Version org.hibernate.annotations.common.Version -HCANN000001: Hibernate Commons Annotations {4.0.1.Final}
1122 [main] INFO  org.hibernate.Version org.hibernate.Version -HHH000412: Hibernate Core {4.1.2}
1125 [main] INFO  org.hibernate.cfg.Environment org.hibernate.cfg.Environment -HHH000206: hibernate.properties not found
1127 [main] INFO  org.hibernate.cfg.Environment org.hibernate.cfg.Environment -HHH000021: Bytecode provider name : javassist
1366 [main] INFO  org.hibernate.dialect.Dialect org.hibernate.dialect.Dialect -HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
1376 [main] WARN  org.hibernate.dialect.H2Dialect org.hibernate.dialect.H2Dialect -HHH000393: The 1.0.44 version of H2 implements temporary table creation such that it commits current transaction; multi-table, bulk hql/jpaql will not work properly
1380 [main] INFO  org.hibernate.engine.jdbc.internal.LobCreatorBuilder org.hibernate.engine.jdbc.internal.LobCreatorBuilder -HHH000423: Disabling contextual LOB creation as JDBC driver reported JDBC version [3] less than 4
1388 [main] INFO  org.hibernate.engine.transaction.internal.TransactionFactoryInitiator org.hibernate.engine.transaction.internal.TransactionFactoryInitiator -HHH000399: Using default transaction strategy (direct JDBC transactions)
1392 [main] INFO  org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory org.hibernate.hql.internal.ast.ASTQueryTranslatorFactory -HHH000397: Using ASTQueryTranslatorFactory
1614 [main] INFO  org.springframework.beans.factory.support.DefaultListableBeanFactory org.springframework.beans.factory.support.DefaultListableBeanFactory -Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@30f7f56b: defining beans [dataSource,sessionFactory,transactionManager,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.transaction.annotation.AnnotationTransactionAttributeSource#0,org.springframework.transaction.interceptor.TransactionInterceptor#0,org.springframework.transaction.config.internalTransactionAdvisor,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.internalPersistenceAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor$ImportAwareBeanPostProcessor#0]; root of factory hierarchy
1623 [main] ERROR org.springframework.test.context.TestContextManager org.springframework.test.context.TestContextManager -Caught exception while allowing TestExecutionListener [org.springframework.test.context.support.DependencyInjectionTestExecutionListener@4099d33d] to prepare test instance [test.TestPersonaDAOImpl@32fb6aed]
java.lang.IllegalStateException: Failed to load ApplicationContext
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:157)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:321)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:288)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:290)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:47)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:231)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:60)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:229)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:50)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:222)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:300)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:675)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in URL [file:/home/rugar/Documents/workspace-sts-3.6.2.RELEASE/struts-spring-hibernate/target/test-classes/datasource-test.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.hibernate.internal.SessionFactoryImpl' to required type 'javax.sql.DataSource' for property 'dataSource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.hibernate.internal.SessionFactoryImpl] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:527)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:294)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:225)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:291)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:193)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:585)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:913)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:464)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:103)
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
    at org.springframework.test.context.support.DelegatingSmartContextLoader.loadContext(DelegatingSmartContextLoader.java:228)
    at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:124)
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:148)
    ... 24 more
Caused by: org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'org.hibernate.internal.SessionFactoryImpl' to required type 'javax.sql.DataSource' for property 'dataSource'; nested exception is java.lang.IllegalStateException: Cannot convert value of type [org.hibernate.internal.SessionFactoryImpl] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found
    at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:485)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:516)
    at org.springframework.beans.BeanWrapperImpl.convertForProperty(BeanWrapperImpl.java:510)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.convertForProperty(AbstractAutowireCapableBeanFactory.java:1406)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyPropertyValues(AbstractAutowireCapableBeanFactory.java:1365)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1118)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:517)
    ... 37 more
Caused by: java.lang.IllegalStateException: Cannot convert value of type [org.hibernate.internal.SessionFactoryImpl] to required type [javax.sql.DataSource] for property 'dataSource': no matching editors or conversion strategy found
    at org.springframework.beans.TypeConverterDelegate.convertIfNecessary(TypeConverterDelegate.java:241)
    at org.springframework.beans.BeanWrapperImpl.convertIfNecessary(BeanWrapperImpl.java:470)
    ... 43 more

测试类:

package test;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;
import java.util.List;
import mx.com.gm.capadatos.PersonaDAO;
import mx.com.gm.capadatos.domain.Persona;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
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 org.springframework.transaction.annotation.Transactional;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:datasource-test.xml", "classpath*:applicationContext.xml"})
public class TestPersonaDAOImpl {
    private static Log logger = LogFactory.getLog("TestPersonaDAOImpl");

    @Autowired
    private PersonaDAO personaDao;

    @Test
    @Transactional
    public void deberiaMostrarPersonas(){

        try{
            System.out.println();
            logger.info("Inicio del Test deberiaMostrarPersonas");
            List<Persona> personas = personaDao.findAllPersonas();
            int contadorPersonas = 0;

            for(Persona persona: personas){
                logger.info("Persona: " + persona);
                contadorPersonas++;
            }

            // Debería de haber la misma cantidad de personas

            assertEquals(contadorPersonas, personaDao.contadorPersonas());
            logger.info("Fin del test deberiaMostrarPersonas");

        }
        catch(Exception e)
        {
            logger.error("Error JBDC", e);

        }
    }

}

这是ApplicationContext:

<?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"
    xmlns:p="http://www.springframework.org/schema/p"
    xmlns:tx="http://www.springframework.org/schema/tx"
    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-3.1.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.1.xsd">

    <tx:annotation-driven/>
    <context:component-scan base-package="mx.com.gm.capaservicio" />
    <context:component-scan base-package="mx.com.gm.capadatos" />

</beans>

这是测试的应用程序上下文:

<?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:jdbc="http://www.springframework.org/schema/jdbc"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.1.xsd">


    <jdbc:embedded-database id="dataSource" type="H2">
        <jdbc:script location="classpath:esquema.sql"/> 
        <jdbc:script location="classpath:datos.sql"/>   
    </jdbc:embedded-database>

    <bean id="sessionFactory"
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"
        p:dataSource-ref="dataSource">
        <property name="packagesToScan">
            <list>
                <value>mx.com.gm.capadatos.domain</value>
            </list>
        </property>

        <property name="hibernateProperties">
            <value>hibernate.format_sql=true hibernate.show_sql=true
            hibernate.dialect=org.hibernate.dialect.H2Dialect</value>
        </property> 
    </bean>
    <bean id="transactionManager"
        class="org.springframework.orm.hibernate4.HibernateTransactionManager"
        p:dataSource-ref="sessionFactory" />

</beans>

工具类

package mx.com.gm.capadatos;

import java.util.List;

import mx.com.gm.capadatos.domain.Persona;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Example;
import org.hibernate.criterion.Projection;
import org.hibernate.criterion.Projections;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;


public class PersonaDAOImpl implements PersonaDAO{
    private SessionFactory sessionFactory;

    @Autowired
    public PersonaDAOImpl(SessionFactory sessionFactory){
        this.sessionFactory = sessionFactory;
    }

    private Session currentSession(){
        return sessionFactory.getCurrentSession();
    }

    public void insertPersona(Persona persona) {
        currentSession().saveOrUpdate(persona);

    }

    public void updatePersona(Persona persona) {
        currentSession().update(persona);

    }

    public void deletePersona(Persona persona) {
        currentSession().delete(persona);

    }

    public Persona findPersonaById(long idPersona) {
        return (Persona) currentSession().get(Persona.class, idPersona);
    }

    @SuppressWarnings("unchecked")
    public List<Persona> findAllPersonas() {
        return currentSession().createQuery("from Persona").list();
    }

    public long contadorPersonas() {
        Long contador = (Long) currentSession().createCriteria(Persona.class)
                .setProjection(Projections.rowCount()).uniqueResult();
        return contador.longValue();
    }

    public Persona getPersonaByEmail(Persona persona) {

        Example persoEjemplo = Example.create(persona);
        return (Persona) currentSession().createCriteria(Persona.class)
                .add(persoEjemplo).uniqueResult();
    }



}

1 个答案:

答案 0 :(得分:0)

您可以使用:

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

如果您想使用HibernateTransactionManager

创建sessionFactory