【发布时间】:2011-05-08 19:05:28
【问题描述】:
我在 spring mvc 和 maven 上有 Web 应用程序。 当我执行“mvn clean install”时,我从一些 uni-test 中得到了 nullpointerexception。 发生这种情况是因为其中一个资源为空,但为什么呢?
联合测试:
package myapp.services.impl
....
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:META-INF/spring/applicationContext.xml"})
@TransactionConfiguration
public class MyServiceImplTest {
@Resource
private MyService myService;
@Transactional
@Test
public void someTest() {
SomeEntity entity = new SomeEntity();
myService.createSomething(entity); // THROW - NullPointerException, myService is NULL
...
}
}
pom.xml 中的surefire 插件:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.4.3</version>
<configuration>
<systemProperties>
<property>
<name>myapp.env</name>
<value>test</value>
</property>
</systemProperties>
<junitArtifactName>org.junit:com.springsource.org.junit</junitArtifactName>
</configuration>
</plugin>
还有applicationContext.xml:
...
<context:component-scan base-package="myapp.services,myapp.services.impl"/>
<context:property-placeholder location="classpath*:META-INF/spring/common_${myapp.env}.properties"
system-properties-mode="OVERRIDE"
ignore-resource-not-found="true"/>
....
PS:当我在 eclipse Run as JUnit Test 中执行这个测试时 - 执行没问题
surefire 报告后的堆栈跟踪:
测试集:myapp.services.impl.MyServiceImplTest
测试运行:1,失败:1,错误:0,跳过:0,经过的时间:1.115 秒
行家输出:
...
[INFO] --- maven-surefire-plugin:2.4.3:test (default-test) @ mywebapp ---
[INFO] Surefire report directory: /home/xxx/Work/mywebapp/target/surefire-reports
-------------------------------------------------------
T E S T S
-------------------------------------------------------
Running myapp.services.impl.MyServiceImplTest
log4j:WARN No such property [maxFileSize] in org.apache.log4j.DailyRollingFileAppender.
log4j:WARN No such property [maxBackupIndex] in org.apache.log4j.DailyRollingFileAppender.
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0, Time elapsed: 0.919 sec <<< FAILURE!
Results :
Failed tests:
myapp.services.impl.MyServiceImplTest.someTest()
Tests run: 1, Failures: 1, Errors: 0, Skipped: 0
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 41.465s
[INFO] Finished at: Mon May 09 00:05:06 MSD 2011
[INFO] Final Memory: 26M/70M
...
【问题讨论】:
-
你能发布堆栈跟踪和测试执行的上下文加载的输出吗?
-
当然!我在“肯定报告后的堆栈跟踪:”之后添加了有问题的输出。但我不认为它有帮助。
-
您还没有附加弹簧上下文加载的输出。如果没有这个,我的猜测是你有一个类路径问题。 application-context.xml 可能不在 Maven 测试类路径上。通常,当某些东西在 Eclipse 中而不是在 Maven 中有效时,我发现就是这种情况。尝试在测试/资源区域复制 application-context.xml。
-
你的意思是maven构建输出还是测试执行输出?我执行 mvn clean install 时没有 spring 上下文输出...
-
"尝试在测试/资源区域复制 application-context.xml" 是的 - 我已经尝试过但没有改变任何东西... :(
标签: java unit-testing spring maven-2 junit