如何在 Spring Boot 应用程序状态启动之前运行 wiremock?

Yac*_*aiz 6 java spring-boot wiremock

我有一个 Spring Boot 微服务的集成测试。问题是该服务在启动时调用外部服务(通过 REST)。我正在使用 WireMock 来模拟调用。Spring 使应用程序在 WireMock 启动之前启动。因此,rest 调用失败,服务也失败。

这个电话是由我们公司的一个图书馆发出的,所以我不能在那里改变任何东西。

你对我有什么建议吗?

Ale*_*981 10

您可能会在测试中创建 WireMockServer 的静态实例。这是一个代码示例:

@RunWith(SpringRunner.class)
@SpringBootTest
public class YourApplicationTests {
    static WireMockServer mockHttpServer = new WireMockServer(10000); // endpoint port here

    @BeforeClass
    public static void setup() throws Exception {
        mockHttpServer.stubFor(get(urlPathMatching("/")).willReturn(aResponse().withBody("test").withStatus(200)));
        mockHttpServer.start();
    }

    @AfterClass
    public static void teardown() throws Exception {
        mockHttpServer.stop();
    }

    @Test
    public void someTest() throws Exception {
        // your test code here
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这仍然会导致引发条件。WireMock 启动可能需要一些时间,因为“start()”不是阻塞操作,并且初始化存根需要一些时间。因此,当测试的第一个请求被触发时,它还没有完全启动。 (2认同)