为什么我无法使用JUnit 4测试我的项目?

时间:2012-01-06 14:28:25

标签: java spring testing junit

我在我的项目中使用Spring 3,Hibernate 3。但我无法使用JUnit 4进行测试。

这是我的Test类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"file:WebRoot/WEB-INF/applicationContext.xml"})
public class UserDaoTestCase extends AbstractJUnit4SpringContextTests {

    @Autowired
    private UserDao userDao;

    @Test
    public void testSimple() {
        // do some tests...
    }



    // setters and getters
    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

}

我运行此测试,我总是得到这个例外:

  

java.lang.IllegalStateException:无法加载ApplicationContext   org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)     在   org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DependencyInjectionTestExecutionListener.java:109)     在   org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DependencyInjectionTestExecutionListener.java:75)     在   org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:333)     在   org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:220)at   org.springframework.test.context.junit4.SpringJUnit4ClassRunner $ 1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)     在   org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)     在   org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)     在   org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)     在   org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)     在org.junit.runners.ParentRunner $ 3.run(ParentRunner.java:193)at   org.junit.runners.ParentRunner $ 1.schedule(ParentRunner.java:52)at at   org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)at at   org.junit.runners.ParentRunner.access $ 000(ParentRunner.java:42)at at   org.junit.runners.ParentRunner $ 2.evaluate(ParentRunner.java:184)at at   org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)     在   org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)     在org.junit.runners.ParentRunner.run(ParentRunner.java:236)at   org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)     在   org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:49)     在   org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)     在   org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)   引起:org.springframework.beans.factory.BeanCreationException:   创建名称为' sessionFactory'的bean时出错在URL中定义   [file:WebRoot / WEB-INF / applicationContext.xml]:调用init   方法失败;嵌套异常是org.hibernate.HibernateException:   无法获取默认Bean验证工厂   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1412)     在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:519)     在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:456)     在   org.springframework.beans.factory.support.AbstractBeanFactory $ 1.getObject(AbstractBeanFactory.java:291)     在   org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)     在   org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:288)     在   org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:190)     在   org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)     在   org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:895)     在   org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:425)     在   org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:84)     在   org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)     在   org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)     在   org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)     ... 24更多引起:org.hibernate.HibernateException:无法执行   获取默认的Bean Validation工厂   org.hibernate.cfg.beanvalidation.BeanValidationActivator.applyDDL(BeanValidationActivator.java:127)     在   org.hibernate.cfg.Configuration.applyBeanValidationConstraintsOnDDL(Configuration.java:1704)     在   org.hibernate.cfg.Configuration.applyConstraintsToDDL(Configuration.java:1654)     在   org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1445)     在   org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)     在   org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:717)     在   org.springframework.orm.hibernate3.AbstractSessionFactoryBean.afterPropertiesSet(AbstractSessionFactoryBean.java:211)     在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1469)     在   org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1409)     ... 37更多引起:java.lang.reflect.InvocationTargetException     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)at   sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)     在   sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)     在java.lang.reflect.Method.invoke(Method.java:597)at   org.hibernate.cfg.beanvalidation.BeanValidationActivator.applyDDL(BeanValidationActivator.java:118)     ... 45更多引起:org.hibernate.HibernateException:无法执行   在,构建默认的ValidatorFactory   org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:383)     在   org.hibernate.cfg.beanvalidation.TypeSafeActivator.applyDDL(TypeSafeActivator.java:109)     ... 50更多引起:javax.validation.ValidationException:无法使用   实例化配置。在   javax.validation.Validation $ GenericBootstrapImpl.configure(Validation.java:272)     在   javax.validation.Validation.buildDefaultValidatorFactory(Validation.java:111)     在   org.hibernate.cfg.beanvalidation.TypeSafeActivator.getValidatorFactory(TypeSafeActivator.java:380)     ... 51更多引起:java.lang.NullPointerException at   java.util.ResourceBundle.getBundle(ResourceBundle.java:960)at   org.hibernate.validator.engine.ResourceBundleMessageInterpolator.loadBundle(ResourceBundleMessageInterpolator.java:202)     在   org.hibernate.validator.engine.ResourceBundleMessageInterpolator.getFileBasedResourceBundle(ResourceBundleMessageInterpolator.java:182)     在   org.hibernate.validator.engine.ResourceBundleMessageInterpolator。(ResourceBundleMessageInterpolator.java:81)     在   org.hibernate.validator.engine.ResourceBundleMessageInterpolator。(ResourceBundleMessageInterpolator.java:73)     在   org.hibernate.validator.engine.ConfigurationImpl。(ConfigurationImpl.java:57)     在   org.hibernate.validator.HibernateValidator.createGenericConfiguration(HibernateValidator.java:43)     在   javax.validation.Validation $ GenericBootstrapImpl.configure(Validation.java:269)     ... 53更多

我的IDE是MyEclipse 9,我使用的是JavaEE 6库。

我认为我的applicationContext.xml没问题,因为我在tomcat中运行这个项目时工作正常,没有例外。

这是我在applicationContext.xml中的SessionFactory bean:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
    <property name="dataSource" ref="c3p0DataSource" />
    <property name="packagesToScan">
        <list>
            <value>com.myproject.entity</value>
        </list>
    </property>
    <property name="hibernateProperties">
        <props>
             <prop key="hibernate.connection.provider_class">
                 org.hibernate.connection.C3P0ConnectionProvider
              </prop>
              <prop key="hibernate.hbm2ddl.auto">update</prop>
              <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
              <prop key="hibernate.show_sql">true</prop>
              <prop key="hibernate.format_sql">true</prop>
       </props> 
    </property>
</bean>

如何正确使用JUnit 4进行测试?

5 个答案:

答案 0 :(得分:6)

我希望你有了错误的 application-context.xml 的路径,就像Spring看到的那样。我首先尝试放弃 WebRoot /

我将Spring源代码附加到我的项目中并连接一个调试器,在线打破:

  

org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)

在那里,您将看到它正在加载应用程序上下文的位置,您可以使用交互式表达式执行程序尝试多个不同的字符串来确定它能够和不能看到的内容。

我也试试这个:

@ContextConfiguration(locations = { "classpath*:applicationContext*.xml" })

我的项目中的工作是在部署中 WEB-INF / classes 中的文件。

答案 1 :(得分:1)

您是否真的使用生产应用程序上下文进行测试?

我会改变使用不同应用程序上下文进行测试的方法(例如,用于定义测试数据源和内容),并将其与其他测试资源一起放置。然后进行简单的查找,如下所示。

@ContextConfiguration("/path/to/my/test-context.xml")

在您的示例中,您必须确保路径正确!您的文件URL应该转换为相对于项目根文件夹的文件夹。申请背景是否存在?

答案 2 :(得分:0)

@ContextConfiguration(locations={"file:WebRoot/WEB-INF/applicationContext.xml"})

我认为您没有从file://找到Spring上下文配置文件。重新找到它。

答案 3 :(得分:0)

我也有这个问题,在我的情况下,问题在于加载了应用程序上下文xml配置文件。它不是一个正确定义的应用程序上下文。确切地说,“xmlns:context =”http://www.springframework.org/schema/context“名称空间丢失了。

答案 4 :(得分:0)

我也有同样的问题,当我更新src / test / resources / ApplicationResource.properties和src / main / resources / ApplicationResource.proerties时。

我更新了POM.xml,其中包含上下文和测试依赖性

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-context</artifactId>
    <version>${org.springframework-version}</version>
</dependency>
<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-test</artifactId>
    <version>${org.springframework-version}</version>
</dependency>

成功加载了src / test / resources / ApplicationContext.xml。

我的问题解决了。