【发布时间】:2021-12-16 00:37:09
【问题描述】:
@ContextConfiguration location 属性对 Spring Boot 集成测试没有意义。有没有其他方法可以跨多个使用 @SpringBootTest 注释的测试类重用应用程序上下文?
【问题讨论】:
标签: java spring spring-boot dependency-injection spring-test
@ContextConfiguration location 属性对 Spring Boot 集成测试没有意义。有没有其他方法可以跨多个使用 @SpringBootTest 注释的测试类重用应用程序上下文?
【问题讨论】:
标签: java spring spring-boot dependency-injection spring-test
是的。 Actually it is default behavior。该链接指向 Spring Framework 文档,Spring Boot 在后台使用该文档。
顺便说一句,在使用@ContextConfiguration 时,默认情况下也会重用上下文。
【讨论】:
@DirtiesContext,我误解了它的作用。我到处都删除了它(无论如何在类设置中都有清理)并且测试运行速度快了 3 分钟,即 30%
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
上面的注释说完整的上下文被加载并且在测试中使用相同的。这意味着它只加载一次。
Spring Boot 提供了一个 @SpringBootTest 注解,当您需要 Spring Boot 功能时,它可以作为标准 spring-test @ContextConfiguration 注解的替代品。注释通过 SpringApplication 创建测试中使用的 ApplicationContext 来工作
【讨论】:
@DirtiesContext 注释,这就是为每个测试类重新启动所有内容的原因。 @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS)我正在调查是否可以删除它,但到目前为止我发现表格存在一些问题
对于像我一样从 Google 登陆的人:
如果您的 Maven surefire 插件中有 <reuseFork>false</reuseFork>,则您的上下文不可能被重用,因为您实际上为每个测试类生成了一个新的 JVM。
这在 Spring 文档中有很好的记录:https://docs.spring.io/spring/docs/current/spring-framework-reference/testing.html#testcontext-ctx-management-caching
【讨论】:
如果您从 Google 登陆,并且在启动多个应用程序上下文时遇到问题,请注意这一点:
确保在多次使用 @SpringBootTests 时使用相同的属性。
例如。如果你有一个简单地使用 @SpringBootTest 的测试和另一个使用 @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) 的测试,每个都会启动它自己的上下文!
最简单的方法是在每个集成测试中扩展一个 BaseIntegrationTest 类,并将 @SpringBootTest 注释放在该基类上,例如:
package com.example.demo;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
public abstract class BaseIntegrationTest{
}
【讨论】: