如何解决Spring Boot 从 2.2.x 升级到 2.4.x:@Test 不再可以通过 application.properties 中的 @activatedProperties@ 访问活动配置文件
我刚刚将一个项目从 Spring Boot 2.2.4.RELEASE 升级到 2.4.5。我有依赖于活动 Spring 配置文件设置的单元测试。
应用属性:
spring.profiles.active=@activatedProperties@
测试现在失败,因为替换不再在测试应用程序上下文中正确发生。
失败的测试:
@ExtendWith(SpringExtension.class)
@SpringBoottest(properties = {"spring.profiles.active=test"})
@ContextConfiguration(classes = Main.class)
@TestPropertySource(locations = "classpath:application-test.properties")
@EnableJpaRepositories(basePackages = {"myco"})
@ActiveProfiles("test")
public class GenericclientTest {
@Value("${spring.profiles.active}")
private String activeProfile; // <-- Now gets set to "@activatedProperties@" instead of "test"
@BeforeEach
public void setUp() {
if (activeProfile.equals("test")) {
doImportantStuff(); // <-- NO LONGER make it to here
}
}
@Test
public void testNumberOne() throws ExecutionException,InterruptedException {
// stuff
}
}
这是pom.xml中的测试依赖,没有变化:
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
我知道 2.4.x 更改了属性文件处理,但是如果通过 @activatedProperties@ 的配置文件替换在运行上下文中仍然有效,为什么它不再适用于 @Test
的?
解决方法
显然,通过 spring.profiles.active
注释设置 @ActiveProfiles("test")
被认为是实现细节并且不可靠。如 this discussion 和 here also 中所示,Spring Boot 从 v2.2.x 升级到 2.3.x 和 2.3.x 到 2.4.x 暴露了这个问题。
最佳做法是在 @SpringBootTest
中明确设置配置文件:
@SpringBootTest(properties = {"spring.profiles.active=test"})
这对我有用。为了升级到 2.4.x,建议在多文档 .properties
文件中创建特定于测试的 application.properties,我也会尝试。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。