首页 > 解决方案 > Java 8 到 Java 11 迁移中的单元测试失败

问题描述

我正在将我的项目从 Java 8 迁移到 Java 11。所以我使用了 Spring 5.1.0、Java 11、Eclipse 4.16 和 Tomcat 9。我能够成功构建源代码。但是当涉及到测试时,他们会失败。

这是我在 pom.xml 中用于测试的内容。

<dependency>
   <groupId>junit</groupId>
   <artifactId>junit</artifactId>
   <version>4.12</version>
   <scope>test</scope>
   <type>jar</type>
</dependency>
<dependency>
   <groupId>org.mockito</groupId>
   <artifactId>mockito-core</artifactId>
   <version>2.27.0</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-module-junit4</artifactId>
   <version>2.0.2</version>
   <scope>test</scope>
</dependency>
<dependency>
   <groupId>org.powermock</groupId>
   <artifactId>powermock-api-mockito2</artifactId>
   <version>2.0.2</version>
   <scope>test</scope>
</dependency> 

而且我的测试用例在 Java 8 中的上述依赖项下运行得非常好。但是当我将代码迁移到 Java 11 时,我得到了以下异常。

ERROR: org.springframework.test.context.TestContextManager - Caught exception while allowing 
TestExecutionListener 
[org.springframework.test.context.support.DependencyInjectionTestExecutionListener@54e063d] to 
prepare test instance [com.test.SomeTest2@4293943]

java.lang.IllegalStateException: Failed to load ApplicationContext
at org.springframework.test.context.support.DefaultTestContext.getApplicationContext(DefaultTestContext.java:122) ~[Spring-test-5.1.0.RELEASE.JAR:5.1.0.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.injectDependencies(DefaultTestCDependencyInjectionTestExecutionListenerontext.java:122) ~[Spring-test-5.1.0.RELEASE.JAR:5.1.0.RELEASE]
at org.springframework.test.context.support.DependencyInjectionTestExecutionListener.prepareTestInstance(DefaDefaultTestCDependencyInjectionTestExecutionListenerontextultTestContext.java:122) ~[Spring-test-5.1.0.RELEASE.JAR:5.1.0.RELEASE]
at org.springframework.test.context.TestContextManager.prepareTestInstance(TestContextManager.java:312) ~[Spring-test-5.1.0.RELEASE.JAR:5.1.0.RELEASE]
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.createTest(SpringJUnit4ClassRunner.java:211) ~[Spring-test-5.1.0.RELEASE.JAR:5.1.0.RELEASE]

我的示例测试类结构

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:test-context.xml"})
public class SomeTestClass {
   ...
}

由于提到的异常,哪个失败了。但是,我做了一些研究并找到了一种解决方法,即改变:

@ContextConfiguration(locations = {"classpath:test-context.xml"})

对此:

@ContextConfiguration(locations = {"classpath*:/spring/test-context.xml"})

它有效。但问题是我不允许编辑源代码。如何实现?

标签: javaeclipsemavenjunitclasspath

解决方案


如果包含“spring”目录的目录是您的类路径中的目录,而不是“spring”目录本身,那么这不是“解决方法”,而是“修复”。如果您不允许更改任何内容,那么您也无法修复任何内容。


推荐阅读