我正在为我的 Spring Boot 服务编写测试。我使用 Wiremock 来模拟 HTTP 请求。我需要暂时禁用 WireMock 服务器来进行一项特定测试,以模拟外部服务不可用的情况。
这是我当前的测试课程:
@SpringBootTest(classes = {ArticleService.class, ArticleServiceTest.TestConfig.class})
@WireMockTest(httpPort = 8080, proxyMode = true)
public class ArticleServiceTest {
@Autowired
private ArticleService articleService;
@TestConfiguration
public static class TestConfig {
@Bean
@Primary
public ArticleServiceConfiguration articleServiceConfiguration() {
ArticleServiceConfiguration configuration = Mockito.mock(ArticleServiceConfiguration.class);
Mockito.when(configuration.getUri()).thenReturn(URI.create("http://article-service:8080"));
return configuration;
}
}
@Test
public void saveArticle() {
// This test works well
String expectedJson = """
{
"title": "Test Title",
"content": "Test Content",
"creatorId": 1
}""";
stubFor(post(urlEqualTo("/internal/articles"))
.withHost(equalTo("article-service"))
.willReturn(ok()));
ArticleDto dto = new ArticleDto("Test Title", "Test Content", 1L);
articleService.saveArticle(dto);
verify(postRequestedFor(urlEqualTo("/internal/articles"))
.withRequestBody(equalToJson(expectedJson)));
}
@Test
public void saveArticleWhenServerIsUnavailable() {
// How to disable the wiremock server here?
ArticleDto dto = new ArticleDto("Test Title", "Test Content", 1L);
assertThrows(ServerUnavailableException.class, () -> articleService.saveArticle(dto));
}
}
那么如何正确停止 WireMock 服务器进行单个测试,同时保持其对其他测试启用?
您可以通过将 WireMock 配置为使用 RST 数据包断开与客户端的连接来模拟 WireMock 关闭的效果。当您尝试连接到未打开的端口时,大多数网络堆栈都会执行以下操作:
stubFor(any(anyUrl())
.willReturn(aResponse().withFault(Fault.CONNECTION_RESET_BY_PEER)));