[英]Testing Spring Cloud Config Server
有沒有關於測試 Spring 雲配置服務器的最佳實踐?
我發現部署到 Kubernetes 時很難正確配置,而且每次修復和重新部署都需要時間。 當進行更改時,還有回歸失敗的問題。
首先,有沒有辦法編寫應用程序上下文將加載的冒煙測試? 與此類似:
@SpringBootTest
@TestPropertySource(properties = { "spring.config.location=classpath:application.yml" })
@Tag("Smoke")
public class TellusIngestionApplicationTests {
@Test
void contextLoads() {
}
}
但不是加載測試 application.yml 文件,而是從 Spring 雲配置服務器加載配置,然后測試不同的配置文件? 例如。 開發階段、生產等
感謝 Spencer 提供的示例代碼!
針對 JUnit5 進行調整,我必須編寫一個自定義擴展來在應用程序上下文啟動之前啟動配置服務器(@BeforeAll 似乎不起作用)。 我最終得到以下代碼:
import com.example.configserver.ConfigServerApplication;
import org.junit.jupiter.api.Nested;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.AfterAllCallback;
import org.junit.jupiter.api.extension.BeforeAllCallback;
import org.junit.jupiter.api.extension.ExtendWith;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.context.ActiveProfiles;
import static org.springframework.boot.test.context.SpringBootTest.WebEnvironment.RANDOM_PORT;
@ExtendWith(ClockApplicationTests.ConfigServerExtension.class)
@SpringBootTest(classes = ClockApplication.class,
// Normally spring.cloud.config.enabled:true is the default but since we have the config server on the classpath
// we need to set it explicitly.
properties = {
"spring.cloud.config.enabled:true",
"management.security.enabled=false",
"management.endpoints.web.exposure.include=*"
},
webEnvironment = RANDOM_PORT)
@Tag("Smoke")
class ClockApplicationTests {
static class ConfigServerExtension implements BeforeAllCallback, AfterAllCallback {
@Override
public void beforeAll(ExtensionContext extensionContext) {
if (server == null) {
server = new SpringApplicationBuilder(ConfigServerApplication.class)
.run("--server.port=" + CONFIG_PORT,
"--spring.cloud.config.server.git.uri=???",
"--spring.cloud.config.server.git.username=???",
"--spring.cloud.config.server.git.password=???",
"--spring.cloud.config.server.git.default-label=master",
"--spring.cloud.config.server.git.search-paths=???");
}
}
@Override
public void afterAll(ExtensionContext extensionContext) {
if (server != null) {
server.close();
}
}
}
private static final int CONFIG_PORT = 8888;
private static ConfigurableApplicationContext server;
@Nested
@ActiveProfiles("docker")
@Tag("docker")
class Docker {
@Test
void contextLoads() {
// The application context will fail to load if the required properties are not found
}
}
@Nested
@ActiveProfiles("kubernetes")
@Tag("kubernetes")
class Kubernetes {
@Test
void contextLoads() {
// The application context will fail to load if the required properties are not found
}
}
}
注意:這假設您沒有為屬性設置默認值。 或者,您可以斷言屬性的值,類似於 Spencer 的示例代碼。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.