2013-08-21 65 views
4

我正试图学习如何在Spring中使用JUnit进行测试。我写了这个测试:在Spring + eclipse中配置JUnit 4

import org.apache.log4j.Logger; 
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 com.blah.baseProject.database.model.Usuario; 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { "file:src/test/resources/test-applicationContext.xml" }) 
public class LoginTest2 { 

    @Autowired 
    UsuarioDAO usuario; 

    private final static Logger logger = Logger.getLogger(LoginTest2.class); 

    @Test 
    public void test() { 

     logger.info("hi "+usuario.findAll()); 
    } 

} 

但我得到这个错误:

ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [or[email protected]54e063d] to prepare test instance [[email protected]] 
java.lang.IllegalStateException: Failed to load ApplicationContext 
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:99) 
    at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:122) 
    at org.springframework.test.context.web.ServletTestExecutionListener.setUpRequestContextIfNecessary(ServletTestExecutionListener.java:105) 
    at org.springframework.test.context.web.ServletTestExecutionListener.prepareTestInstance(ServletTestExecutionListener.java:74) 
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312) 
    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:284) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) 
    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:467) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) 
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'myDataSource': Invocation of init method failed; nested exception is javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1482) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:521) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458) 
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295) 
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292) 
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:608) 
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932) 
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479) 
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:120) 
    at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:60) 
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.delegateLoading(AbstractDelegatingSmartContextLoader.java:100) 
    at org.springframework.test.context.support.AbstractDelegatingSmartContextLoader.loadContext(AbstractDelegatingSmartContextLoader.java:248) 
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContextInternal(CacheAwareContextLoaderDelegate.java:64) 
    at org.springframework.test.context.CacheAwareContextLoaderDelegate.loadContext(CacheAwareContextLoaderDelegate.java:91) 
    ... 25 more 
Caused by: javax.naming.NoInitialContextException: Need to specify class name in environment or system property, or as an applet parameter, or in an application resource file: java.naming.factory.initial 
    at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:662) 
    at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:307) 
    at javax.naming.InitialContext.getURLOrDefaultInitCtx(InitialContext.java:344) 
    at javax.naming.InitialContext.lookup(InitialContext.java:411) 
    at org.springframework.jndi.JndiTemplate$1.doInContext(JndiTemplate.java:154) 
    at org.springframework.jndi.JndiTemplate.execute(JndiTemplate.java:87) 
    at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:152) 
    at org.springframework.jndi.JndiTemplate.lookup(JndiTemplate.java:178) 
    at org.springframework.jndi.JndiLocatorSupport.lookup(JndiLocatorSupport.java:95) 
    at org.springframework.jndi.JndiObjectLocator.lookup(JndiObjectLocator.java:105) 
    at org.springframework.jndi.JndiObjectFactoryBean.lookupWithFallback(JndiObjectFactoryBean.java:201) 
    at org.springframework.jndi.JndiObjectFactoryBean.afterPropertiesSet(JndiObjectFactoryBean.java:187) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1541) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1479) 

这是我的applicationContext.xml:

<?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:jee="http://www.springframework.org/schema/jee" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 
    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/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd 
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"> 


    <!-- JDBC Data Source --> 

    <jee:jndi-lookup id="myDataSource" jndi-name="java:comp/env/jdbc/rhcimax"/> 

    <!-- Hibernate Session Factory --> 
    <bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
    <property name="dataSource" ref="myDataSource"/> 
    <property name="packagesToScan"> 
     <array> 
     <value>com.blah.baseProject</value> 
     </array> 
    </property> 
    <property name="hibernateProperties"> 
     <value> 
     hibernate.dialect=org.hibernate.dialect.MySQLDialect 
     </value> 
    </property> 
    </bean> 

    <!-- Hibernate Transaction Manager --> 
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
    <property name="sessionFactory" ref="mySessionFactory"/> 
    </bean> 

    <!-- Activates annotation based transaction management --> 
    <tx:annotation-driven transaction-manager="transactionManager"/> 

    <context:component-scan base-package="com.blah.baseProject"> 
    <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/> 
    </context:component-scan> 

</beans> 

我几乎失去了这一切,任何帮助将不胜感激。

编辑:

这是我UsuarioDAO:

import java.util.List; 

import org.hibernate.SessionFactory; 
import org.springframework.beans.factory.annotation.Autowired; 
import org.springframework.stereotype.Repository; 
import org.springframework.stereotype.Service; 
import org.springframework.transaction.annotation.Transactional; 

import com.blah.baseProject.database.DAO.UsuarioDAO; 
import com.blah.baseProject.database.model.Usuario; 


@Repository(value="UsuarioDao") 
public class UsuarioHibernateDAO implements UsuarioDAO{ 

    @Autowired 
    private SessionFactory mySessionFactory; 

    public void insert(Usuario user) { 
     mySessionFactory.getCurrentSession().save(user); 
    } 

    public void update(Usuario user) { 
     mySessionFactory.getCurrentSession().update(user); 
    } 

    /** 
    * @Transactional annotation below will trigger Spring Hibernate transaction manager to automatically create 
    * a hibernate session. See src/main/webapp/servlet-context.xml 
    */ 
    @Transactional 
    public List<Usuario> findAll() { 
     return mySessionFactory.getCurrentSession().createQuery("from Usuario").list(); 
    } 

    public Usuario findById(String idUser) { 
     return (Usuario) mySessionFactory.getCurrentSession().load(Usuario.class, idUser); 
    } 

    public void delete(Usuario user) { 
     mySessionFactory.getCurrentSession().delete(user); 
    } 


} 

EDIT2:

//src/main/webapp/WEB-INF/applicationContext.xml

<?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:jee="http://www.springframework.org/schema/jee" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 
    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/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd 
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"> 


    <!-- JDBC Data Source--> 
    <jee:jndi-lookup id="myDataSource" jndi-name="java:comp/env/jdbc/rhcimax"/> 

    <!-- Hibernate Session Factory --> 
    <bean id="mySessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 
    <property name="dataSource" ref="myDataSource"/> 
    <property name="packagesToScan"> 
     <array> 
     <value>com.blah.baseProject.test</value> 
     </array> 
    </property> 
    <property name="hibernateProperties"> 
     <value> 
     hibernate.dialect=org.hibernate.dialect.MySQLDialect 
     </value> 
    </property> 
    </bean> 

    <!-- Hibernate Transaction Manager --> 
    <bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 
    <property name="sessionFactory" ref="mySessionFactory"/> 
    </bean> 

    <!-- Activates annotation based transaction management --> 
    <tx:annotation-driven transaction-manager="transactionManager"/> 

    <context:component-scan base-package="com.blah.baseProject.test"> 
    <context:exclude-filter expression="org.springframework.stereotype.Controller" type="annotation"/> 
    </context:component-scan> 

</beans> 

//src/main/test/resources/test-applicationContext.xml

<?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:jee="http://www.springframework.org/schema/jee" 
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:beans="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" 
    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/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd 
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd 
    http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee.xsd"> 


    <!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with 
     username root and blank password. Change below if it's not the case --> 
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 
    <property name="url" value="jdbc:mysql://localhost:3306/rhcimax"/> 
    <property name="username" value="root"/> 
    <property name="password" value="1234"/> 
    <property name="validationQuery" value="SELECT 1"/> 
    </bean> 


</beans> 

//loginTest2.java

import org.apache.log4j.Logger; 
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 com.blah.baseProject.database.DAO.UsuarioDAO; 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/applicationContext.xml", "classpath:test-applicationContext.xml" }) 

public class LoginTest2 { 

    @Autowired 
    UsuarioDAO usuarioDao; 

    private final static Logger logger = Logger.getLogger(LoginTest2.class); 

    @Test 
    public void test() { 

     logger.info("hi "+usuarioDao.findAll()); 
    } 

} 

新的异常:

ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing TestExecutionListener [org.springframewor[email protected]67beff98] to prepare test instance [[email protected]] 
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'com.blah.baseProject.test.LoginTest2': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.blah.baseProject.database.DAO.UsuarioDAO com.blah.baseProject.test.LoginTest2.usuarioDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.blah.baseProject.database.DAO.UsuarioDAO] 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)} 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:288) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.populateBean(AbstractAutowireCapableBeanFactory.java:1116) 
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireBeanProperties(AbstractAutowireCapableBeanFactory.java:376) 
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:110) 
    at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75) 
    at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312) 
    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:284) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231) 
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88) 
    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:467) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390) 
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197) 
Caused by: org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.blah.baseProject.database.DAO.UsuarioDAO com.blah.baseProject.test.LoginTest2.usuarioDao; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.blah.baseProject.database.DAO.UsuarioDAO] 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)} 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:514) 
    at org.springframework.beans.factory.annotation.InjectionMetadata.inject(InjectionMetadata.java:87) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor.postProcessPropertyValues(AutowiredAnnotationBeanPostProcessor.java:285) 
    ... 26 more 
Caused by: org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.blah.baseProject.database.DAO.UsuarioDAO] 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)} 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.raiseNoSuchBeanDefinitionException(DefaultListableBeanFactory.java:986) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.doResolveDependency(DefaultListableBeanFactory.java:856) 
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.resolveDependency(DefaultListableBeanFactory.java:768) 
    at org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor$AutowiredFieldElement.inject(AutowiredAnnotationBeanPostProcessor.java:486) 
    ... 28 more 
INFO : org.springframework.context.support.GenericApplicationContext - Closing [email protected]427975: startup date [Thu Aug 22 09:22:47 VET 2013]; root of context hierarchy 
INFO : org.springframework.beans.factory.support.DefaultListableBeanFactory - Destroying singletons in org.s[email protected]2af0b852: defining beans [myDataSource,mySessionFactory,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.importAwareProcessor]; root of factory hierarchy 

SOLUTION:

我的测试:

import java.util.List; 

import org.apache.log4j.Logger; 
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 com.blah.baseProject.database.DAO.UsuarioDAO; 
import com.blah.baseProject.database.model.Usuario; 

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { "file:src/main/webapp/WEB-INF/applicationContext.xml", "classpath:test-applicationContext.xml" }) 
@TransactionConfiguration(transactionManager="transactionManager") 
public class LoginTest2 extends AbstractTransactionalJUnit4SpringContextTests { 

    @Autowired 
    UsuarioDAO usuarioDao; 

    private final static Logger logger = Logger.getLogger(LoginTest2.class); 

    @Test 
    public void test() { 
     List<Usuario> a = usuarioDao.findAll(); 

     logger.info("hi "+a.get(0).getLogin()); 
    } 

} 

test-applicationContext.xml和applicationContext.xml保持与对此问题进行编辑时所指定的相同。

+0

除非我失去了一些东西,它看起来像你试图访问你的jndi提供的数据源之外的容器。以[编程方式创建](https://blogs.oracle.com/randystuph/entry/injecting_jndi_datasources_for_junit),或者使用类似本地数据源的东西进行测试。 – ikumen

+0

是的我已经注意到,我试图改变我的上下文应用程序,但我仍然无法使它的工作。 T编辑了这个问题 – kiduxa

+0

是你的新组件扫描'base-package =“com.blah.baseProject.test”'正确吗?包是否包含UsuarioHibernateDAO实现? – ikumen

回答

3

您的测试配置应该只覆盖您在测试中没有的bean(即您的数据源)。接下来,您应该使用前缀classpath:加载您的测试配置文件。

更改您的测试applicationContext.xml文件以下,这将覆盖数据源中的applicationContext.xml中

<!-- JDBC Data Source. It is assumed you have MySQL running on localhost port 3306 with 
    username root and blank password. Change below if it's not the case --> 
<bean id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> 
    <property name="driverClassName" value="com.mysql.jdbc.Driver"/> 
    <property name="url" value="jdbc:mysql://localhost:3306/myDb"/> 
    <property name="username" value="root"/> 
    <property name="password" value="1234"/> 
    <property name="validationQuery" value="SELECT 1"/> 
</bean> 

现在在你的测试用例负荷这两个文件

@RunWith(SpringJUnit4ClassRunner.class) 
@ContextConfiguration(locations = { "classpath:applicationContext.xml", "classpath:test-applicationContext.xml" }) 
public class LoginTest2 { ... } 

的问题您当前的设置是您的test-configuration.xml是您的applicationContext.xml的(错误)副本,这是您应该避免的。如果您正在编写测试,您还应该加载正常的applicationContext.xml文件并覆盖您不需要的bean。

+0

我已经完成了你所说的。我用“Edit2”编辑了quiestion。 – kiduxa

+0

我真的不知道这个..我在UsuarioDAO的定义中有'@'仓库,我已经可以在'@'控制器中使用它了。为什么不工作? :'( – kiduxa

+0

我已经使它成功了,但你的解决方案是我所做的一部分,所以谢谢。 – kiduxa

相关问题