开发者

Spring - unit tests

I followed the instructions at "Unit Testing with Junit, Spring and Hibernate – Part 2".

I created my simple test class:

package com.bontade.tests.unit.models;

import org.hibernate.SessionFactory;
import org.springframework.orm.hibernate3.SessionFactoryUtils;
import org.springframework.test.AbstractTransactionalDataSourceSpringContextTests;

import com.bontade.mvc.models.User;
import com.bontade.mvc.models.dao.implementations.UserDAOImplementation;

public class UserDAOTest extends
    AbstractTransactionalDataSourceSpringContextTests {

private UserDAOImplementation userDAO;
private SessionFactory sessionFactory;

/*
public UserDAOTest() {
    setDependencyCheck(false);
    setAutowireMode(AUTOWIRE_BY_NAME); 
}
*/

public void setUserDAO(UserDAOImplementation userDAO) {
    this.userDAO = userDAO;
}

public void setSessionFactory(SessionFactory sessionFactory) {
    this.sessionFactory = sessionFactory;
}

protected String[] getConfigLocations() {
    // classpath*:/src/test/java/com/bontade/tests/unit/models/test-spring-  config.xml
    return new String[] { "classpath*:/**/test-spring-config.xml" };
}

public void testSave() {
    String query = "SELECT COUNT(*) FROM User WHERE name = 'Mark'";
    int count = this.jdbcTemplate.queryForInt(query);
    assertEquals("A user already exists in the DB", 0, count);

    User user = new User();
    user.setId(null);
    user.setName("Mark");
    user.setGender("Man");
    user.setSurname("Surname");
    user.setPassword("X");

    userDAO.saveUser(user);

    // flush the session so we can get the record using JDBC template
    SessionFactoryUtils.getSession(sessionFactory, false).flush();

    count = jdbcTemplate.queryForInt(query);
    assertEquals("User was not found in the DB", 1, count);
}
}

My configuration file:

<?xml version="1.0" encoding="UTF-8"?>

<beans xmlns="http://www.springframework.org/schema/beans" 
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
       http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<bean id="dataSource"
    class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    <property name="driverClassName" value="org.h2.Driver" />
    <property name="url"
        value="jdbc:h2:tcp://localhost/~/bontade_database_h2" />
    <property name="username" value="ab" />
    <property name="password" value="ab" />
</bean>

<bean id="sessionFactory"
        class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="annotatedClasses">
        <list>
            <value>com.bontade.mvc.models.User</value>
        </list>
    </property>
</bean>

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

<bean id="userDAO"
    class="com.bontade.mvc.models.dao.implementations.UserDAOImplementation">
    <property name="sessionFactory" ref="sessionFactory" />
    <property name="transactionTemplate">
        <bean     class="org.springframework.transaction.support.TransactionTemplate">
            <property name="transactionManager" ref="transactionManager" />
        </bean>
    </property>
</bean>

Both files are placed inside the src/test/java directory in the com.bontade.tests.unit.models package. UserDAO and UserDAOImplementation are placed in the src/main/java directory.

I'm getting error like this:

-------------------------------------------------------------------------------
Test set: com.bontade.tests.unit.models.UserDAOTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.297 sec <<< FAILURE!
testSave(com.bontade.tests.unit.models.UserDAOTest)  Time elapsed: 0.202 sec  <<< ERROR!
org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'com.bontade.tests.unit.models.UserDAOTest': Unsatisfied dependency expressed through bean property 'dataSource': Set this property value or disable dependency checking for this bean.
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.checkDependencies(AbstractAutowireCapableBeanFactory.java:1184)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1006)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:329)
    at org.springframework.test.AbstractDependencyInjectionSpringContextTests.injectDependencies(AbstractDependencyInjectionSpringContextTests.java:205)
    at org.springframework.test.AbstractDependencyInjectionSpringContextTests.prepareTestInstance(AbstractDependencyInjectionSpringContextTests.java:180)
    at org.springframework.test.AbstractSingleSpringContextTests.setUp(AbstractSingleSpringContextTests.java:100)
    at junit.framework.TestCase.runBare(TestCase.java:125)
    at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:76)
    at junit.framework.TestResult$1.protect(TestResult.java:106)
    at junit.framework.TestResult.runProtected(TestResult.java:124)
    at junit.framework.TestResult.run(TestResult.java:109)
    at junit.framework.TestCase.run(TestCase.java:118)
    at junit.framework.TestSuite.runTest(TestSuite.java:208)
    at junit.framework.TestSuite.run(TestSuite.java:203)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.maven.surefire.junit.JUnitTestSet.execute(JUnitTestSet.java:207)
    at org.apache.maven.surefire.junit.JUnit3Provider.executeTestSet(JUnit3Provider.java:107)
    at org.apache.maven.surefire.junit.JUnit3Provider.invoke(JUnit3Provider.java:79)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.maven.surefire.booter.ProviderFactory$ClassLoaderProxy.invoke(ProviderFactory.java:103)
    at $Proxy0.invoke(Unknown Source)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:145)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcess(SurefireStarter.java:87)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:69)

Does anybody know the reason why?


UPDATE:

After reading @Ritesh's clue, I moved "test-spring-config.xml" into the src/test/resources directory and now I see a file in the target/test-classes folder, but I got a new error:

-------------------------------------------------------------------------------
Test set: com.bontade.tests.unit.models.UserDAOTest
-------------------------------------------------------------------------------
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.572 sec <<< FAILURE!
testSave(com.bontade.tests.unit.models.UserDAOTest)  Time elapsed: 0.474 sec  <<< ERROR!
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in file [/home/adam/workspace/CarRentalMaven2XSLTJSPTiles2Tomcat/target/test-classes/test-spring-config.xml]: Invocation of init method failed; nested exception is java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/InheritanceType
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1338)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:473)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory$1.run(AbstractAutowireCapableBeanFactory.java:409)
    at java.security.AccessController.doPrivileged(Native Method)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:380)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:264)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:261)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:185)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:164)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:423)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:728)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:380)
    at org.springframework.test.AbstractSingleSpringContextTests.createApplicationContext(AbstractSingleSpringContextTests.java:213)
    at org.springframework.test.AbstractSingleSpringContextTests.loadContextLocations(AbstractSingleSpringContextTests.java:189)
    at org.springframework.test.AbstractSingleSpringContextTests.loadContext(AbstractSingleSpringContextTests.java:169)
    at org.springframework.test.AbstractSpringContextTests.getContext(AbstractSpringContextTests.java:140)
    at org.springframework.test.AbstractSingleSpringContextTests.setUp(AbstractSingleSpringContextTests.java:98)
    at junit.framework.TestCase.runBare(TestCase.java:132)
    at org.springframework.test.ConditionalTestCase.runBare(ConditionalTestCase.java:76)
    at junit.framework.TestResult$1.protect(TestResult.java:110)
    at junit.framework.TestResult.runProtected(TestResult.java:128)
    at junit.framework.TestResult.run(TestResult.java:113)
    at junit.framework.TestCase.run(TestCase.java:124)
    at junit.framework.TestSuite.runTest(TestSuite.java:243)
    at junit.framework.TestSuite.run(TestSuite.java:238)
    at org.junit.internal.runners.JUnit38ClassRunner.run(JUnit38ClassRunner.java:83)
    at org.apache.maven.surefire.junit4.JUnit4TestSet.execute(JUnit4TestSet.java:35)
    at org.apache.maven.surefire.junit4.JUnit4Provider.executeTestSet(JUnit4Provider.java:146)
    at org.apache.maven.surefire.junit4.JUnit4Provider.invoke(JUnit4Provider.java:97)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at org.apache.maven.surefire.booter.ProviderFactory$ClassLoaderProxy.invoke(ProviderFactory.java:103)
    at $Proxy0.invoke(Unknown Source)
    at org.apache.maven.surefire.booter.SurefireStarter.invokeProvider(SurefireStarter.java:145)
    at org.apache.maven.surefire.booter.SurefireStarter.runSuitesInProcess(SurefireStarter.java:87)
    at org.apache.maven.surefire.booter.ForkedBooter.main(ForkedBooter.java:69)
Caused by: java.lang.ClassFormatError: Absent Code attribute in method that is not native or abstract in class file javax/persistence/InheritanceType
    at java.lang.ClassLoader.defineClass1(Native Method)
    at java.lang.ClassLoader.defineClassCond(ClassLoader.java:632)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:616)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:141)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:283)
    at java.net.URLClassLoader.access$000(URLClassLoader.java:58)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:197)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:307)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:248)
    at org.hibernate.cfg.InheritanceState.extractInheritanceType(InheritanceState.java:51)
    at org.hibernate.cfg.InheritanceState.<init>(InheritanceState.java:21)
    at org.hibernate.cfg.AnnotationBinder.buildInheritanceStates(AnnotationBinder.java:2295)
    at org.hibernate.cfg.AnnotationConfiguration.processArtifactsOfType(AnnotationConfiguration.java:540)
    at org.hibernate.cfg.AnnotationConfiguration.secondPassCompile(AnnotationConfiguration.java:291)
    at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1162)
    at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:673)
    at org.springframework.orm开发者_运维技巧.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1369)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1335)
    ... 38 more

This is what my maven console generates:

-------------------------------------------------------
 T E S T S
-------------------------------------------------------
Running com.bontade.tests.unit.models.UserDAOTest
SLF4J: Class path contains multiple SLF4J bindings.
SLF4J: Found binding in [jar:file:/home/adam/.m2/repository/org/slf4j/slf4j-log4j12/1.6.1/slf4j-log4j12-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/adam/.m2/repository/org/slf4j/slf4j-simple/1.6.1/slf4j-simple-1.6.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/adam/.m2/repository/org/slf4j/slf4j-nop/1.5.3/slf4j-nop-1.5.3.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/home/adam/.m2/repository/org/slf4j/slf4j-jdk14/1.5.6/slf4j-jdk14-1.5.6.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: See http://www.slf4j.org/codes.html#multiple_bindings for an explanation.
log4j:WARN No appenders could be found for logger (com.bontade.tests.unit.models.UserDAOTest).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
Tests run: 1, Failures: 0, Errors: 1, Skipped: 0, Time elapsed: 0.572 sec <<< FAILURE!

Does it mean that I don't have the required jars in my classpath?


The solution was to use

org.springframework.orm.hibernate3.LocalSessionFactoryBean

instead of

org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜