領先一步
VMware 提供培訓和認證,以加速您的進展。
了解更多最近,在 Spring IO 和 SpringOne Platform 上談論測試 Spring Boot 應用程式時,我提到了 Testcontainers,並且 討論了 配置測試以使用在容器內運行的服務所涉及的樣板程式碼。我很高興地說,隨著 最近 Spring Framework 5.2.5 的發布,這些樣板程式碼已不復存在。
在我們剛發布的變更之前,您的整合測試看起來會類似於以下內容
@SpringBootTest
@Testcontainers
@ContextConfiguration(initializers = ExampleIntegrationTests.Initializer.class)
class ExampleIntegrationTests {
@Container
static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
static class Initializer implements
ApplicationContextInitializer<ConfigurableApplicationContext> {
@Override
public void initialize(ConfigurableApplicationContext context) {
TestPropertyValues.of("spring.data.neo4j.uri=" + neo4j.getBoltUrl())
.applyTo(context.getEnvironment());
}
}
}
在這裡,我們使用 @ContextConfiguration
來指定 ApplicationContextInitializer
。初始化器正在使用 Neo4j 容器的 bolt URL 值來配置 spring.data.neo4j.uri
屬性。這允許我們應用程式中與 Neo4j 相關的 bean 與在 Testcontainers 管理的 Docker 容器中運行的 Neo4j 進行通訊。
感謝 Spring Framework 5.2.5 中所做的變更,可以使用靜態 @DynamicPropertySource
方法來取代 @ContextConfiguration
和 ApplicationContextInitializer
的使用,該方法具有相同目的。如果我們對上面顯示的整合測試類別進行這些變更,它現在看起來像這樣
@SpringBootTest
@Testcontainers
class ExampleIntegrationTests {
@Container
static Neo4jContainer<?> neo4j = new Neo4jContainer<>();
@DynamicPropertySource
static void neo4jProperties(DynamicPropertyRegistry registry) {
registry.add("spring.data.neo4j.uri", neo4j::getBoltUrl);
}
}
我們將程式碼量減少了三分之一,並且希望意圖也更加清晰。
雖然新功能的靈感來自於使 Testcontainers 在 Spring Boot 整合測試中更易於使用,但它應該在任何屬性的值事先未知情況下的基於 Spring 的整合測試中都很有用。您可以在 Spring Framework 參考文檔中了解有關 @DynamicPropertySource
的更多資訊。
整合測試愉快!