Java 8到11的迁移中,单元测试失败

6

我正在将我的项目从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"})

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


1
“不允许编辑源代码”是什么意思?你和程序员谈过了吗?你和你的老板谈过这件事吗? - J Fabian Meier
准确地说,“不允许更改源代码”是什么意思?你正在进行迁移工作,对吧?那么,在这种情况下,你必须修改源代码。 - Anish B.
请通过 Github 提供代码库。 - Anish B.
2个回答

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

0
根据您的修复,似乎test-context.xml现在位于classpath*:/spring/test-context.xml。因此,您可以尝试将包含test-context.xml的spring文件夹添加到类路径中,然后它应该可以工作。此解决方案不需要进行代码更改。您可以阅读如何将目录添加到eclipse类路径?以了解如何执行此操作。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接