如何在Junit测试中自动装配(一般Newb查询)

时间:2014-04-09 20:01:54

标签: java spring hibernate unit-testing junit

这是关于Spring和创建应用程序上下文的一般性问题。

我正在为网站应用程序进行单元测试。该网站使用Spring和Hibernate,我想用数据库中的一些数据进行测试。我不知道如何将Spring IOC容器连接到我的单元测试。我知道applicationContext.xml的位置,但是如何在单元测试中访问其bean?

这是我的代码:

package com.example.test;

import junit.framework.Assert;
import org.hibernate.SessionFactory;
import org.hibernate.classic.Session;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;

public class SessionFactoryTest {

    @Autowired
    SessionFactory sessionFactory;

    @Test
    public void testSessionFactoryAutowiring() {
         Session session = sessionFactory.getCurrentSession();
         Assert.assertEquals(session.getClass(),Session.class);
    }
}

哪会产生错误

Testsuite: com.example.test.SessionFactoryTest
Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0.011 sec

Testcase: testSessionFactoryAutowiring took 0.002 sec
Caused an ERROR
null
java.lang.NullPointerException
at com.example.test.SessionFactoryTest.testSessionFactoryAutowiring(SessionFactoryTest.java:19)

现在我的问题是,如何从普通的applicationContex.xml访问sessionFactory?如何访问容器?我不介意创造我自己的,但到今天结束时我真的很想写单元测试。谁不会?

更新:我确实根据Spring文档将注释添加到我的测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext.xml"})

但无法找到该文件,我不知道如何指定相对于我的测试的文件。

Testsuite: com.example.test.SessionFactoryTest
Tests run: 1, Failures: 0, Errors: 1, Time elapsed: 0.045 sec

Testcase: testSessionFactoryAutowiring took 0.035 sec
Caused an ERROR
Failed to load ApplicationContext
java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:308)
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:220)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner$1.runReflectiveCall(SpringJUnit4ClassRunner.java:301)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.methodBlock(SpringJUnit4ClassRunner.java:303)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:240)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:180)
Caused by: org.springframework.beans.factory.BeanDefinitionStoreException: IOException parsing XML document from class path resource [applicationContext.xml]; nested exception is java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:341)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:302)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:143)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:178)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:149)
at org.springframework.beans.factory.support.AbstractBeanDefinitionReader.loadBeanDefinitions(AbstractBeanDefinitionReader.java:212)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:81)
at org.springframework.test.context.support.AbstractGenericContextLoader.loadContext(AbstractGenericContextLoader.java:1)
at org.springframework.test.context.TestContext.loadApplicationContext(TestContext.java:280)
at org.springframework.test.context.TestContext.getApplicationContext(TestContext.java:304)
Caused by: java.io.FileNotFoundException: class path resource [applicationContext.xml] cannot be opened because it does not exist
at org.springframework.core.io.ClassPathResource.getInputStream(ClassPathResource.java:158)
at org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:328)

我的项目结构如下:

src/
web/WEB-INF/applicationContext.xml
test/java/com/example/SessionFactoryTest.java

用蚂蚁建造。

4 个答案:

答案 0 :(得分:0)

在位置中使用classpath将无效,因为您没有使用applicationContext.xml的默认位置

但这可能会奏效。

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "src/stuff web/WEB-INF/applicationContext.xml" })
public class SessionFactoryTest {

我想你的应用程序上下文文件中也有这个:

<context:component-scan base-package="com.example" />

<bean id="sessionFactory" class="com.example.SessionFactoryImpl" />

答案 1 :(得分:0)

您需要声明一个弹簧测试上下文并使用@Runwith进行注释。 xml来到src / test / resources / my-test-config.xml

@RunWith(SpringJunit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:my-test-config.xml"})
public class myTest { ...

编辑:我不确定,但我想你需要将hibernate jar添加到测试范围的类路径中

答案 2 :(得分:0)

我设置类路径以在我的ant build.xml中包含web目录,现在找到applicationContext.xml。现在我有其他问题。特别是主applicationContext.xml中的jndi引用。所有这些都说完了,这就是最终的蚂蚁任务

<target name="test-platform" depends="compile_tests">
    <mkdir dir="${platform.test.log.dir}"/>
    <junit fork="true" haltonerror="true">
        <classpath refid="test.build.classpath"/>
        <classpath location="test"/>
        <classpath location="${build_testclassdir}"/>
        <batchtest todir="${platform.test.log.dir}">
            <formatter type="plain" usefile="true"/>
            <fileset dir="${javatests}">
                <include name="**/*Test.java"/>
            </fileset>
        </batchtest>
    </junit>
</target>

然后在我的一个测试中

@Transactional
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:resources/test-applicationContext.xml"})

并将测试上下文放在test / resources目录中

[david@david web]$ ll test/resources/test-applicationContext.xml 
-rw-rw-r-- 1 david david 4851 Apr  9 16:02 test/resources/test-applicationContext.xml

答案 3 :(得分:0)

对于您的示例代码,您应该在会话工厂单元测试中测试SessionFactory的返回值。

如果要在单元测试中注入依赖项,请考虑使用MockitoAnnotations之类的东西自动将模拟对象注入到测试类中