我有一个Java项目,我正在编写一个简单的JUNIT测试用例。我已将applicatinoContext.xml文件复制到root java源目录中。我已经尝试了一些我在StackOverflow上阅读的推荐设置,但仍然得到相同的错误。这个错误是由于我的项目是一个java项目而不是一个Web项目,或者这甚至是否重要?我不确定我哪里出错了。
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={"C:/projs/sortation/src/main/java/applicationContext.xml"})
// Also tried these settings but they also didnt work,
//@ContextConfiguration(locations={"classpath:applicationContext.xml"})
//@ContextConfiguration("classpath:applicationContext.xml")
@Transactional
public class TestSS {
@Autowired
private EmsDao dao;
@Test
public void getSites() {
List<String> batchid = dao.getList();
for (String s : batchid) {
System.out.println(s);
}
}
}
答案 0 :(得分:27)
看起来你正在使用maven(src/main/java)
。在这种情况下,将applicationContext.xml
文件放在src/main/resources
目录中。它将被复制到classpath目录中,你应该能够使用
@ContextConfiguration("/applicationContext.xml")
来自Spring-Documentation:普通路径(例如“context.xml”)将被视为来自定义测试类的同一包中的类路径资源 。以斜杠开头的路径被视为完全限定的类路径位置,例如“/org/example/config.xml”。
因此,在引用类路径根目录中的文件时添加斜杠非常重要。
如果您使用绝对文件路径,则必须使用'file:C:...'(如果我正确理解文档)。
答案 1 :(得分:3)
我遇到了同样的问题,我正在使用以下插件进行测试:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.9</version>
<configuration>
<useFile>true</useFile>
<includes>
<include>**/*Tests.java</include>
<include>**/*Test.java</include>
</includes>
<excludes>
<exclude>**/Abstract*.java</exclude>
</excludes>
<junitArtifactName>junit:junit</junitArtifactName>
<parallel>methods</parallel>
<threadCount>10</threadCount>
</configuration>
</plugin>
测试在IDE(eclipse sts)中正常运行,但在使用命令 mvn test 时失败。
经过大量的反复试验,我认为解决方案是删除并行测试,以下两行来自上面的插件配置:
<parallel>methods</parallel>
<threadCount>10</threadCount>
希望这可以帮助别人!
答案 2 :(得分:1)
我遇到了这个问题因为during bootstrapping my spring project
使用实现ApplicationListener<ContextRefreshedEvent>
的类和onApplicationEvent
函数中的类会抛出异常
因此请确保您的应用程序引导点不会抛出任何异常
在我的情况下,我使用maven surefire plugin进行测试,以便调试测试过程使用此命令
mvn -Dmaven.surefire.debug test
答案 3 :(得分:-1)
我遇到了这个问题,那就是 Bean (@Bean) 没有正确实例化,因为它没有在我的测试类中提供正确的参数。