问题描述
我刚刚将一个项目从 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,我也会尝试。