【问题标题】:MockServer with test specific session id具有测试特定会话 ID 的 MockServer
【发布时间】:2023-02-14 11:11:17
【问题描述】:

我使用 Spring Boot 和 Java 为我的 API 编写 e2e 测试。 在流程中,我正在对存储 API (S3) 执行 HTTP 调用,并使用 MockServer 对其进行模拟。

这是 HttpClient 以及我如何创建我的发布请求:

public class HttpClient {

    private final String baseUrl;

    public <T> Mono<T> post(final String path, String body, Class<T> responseType) {
        return WebClient.builder()
            .baseUrl(baseUrl) // localhost:1082
            .build()
            .post()
            .uri(path)
            .bodyValue(body)
            .accept(MediaType.APPLICATION_JSON)
...

这就是我配置模拟服务器的方式:

public class CommonMockServerHelpers {

    private static MockServerClient mockServerClientStorage = new MockServerClient("localhost", 1082).reset();

    public static MockServerClient getClientStorage() {
        return mockServerClientStorage;
    }

    public static void verify(String path, String exceptedRequestBody, int times) {
        Awaitility.await()
            .atMost(Duration.ofSeconds(60))
            .untilAsserted(() ->
                verify(getClientStorage(), path, exceptedRequestBody, times)
            );
    }

    public static void verify(MockServerClient client, String path, String exceptedRequestBody, int times) {
        client.verify(buildPostRequest()
            .withBody(subString(exceptedRequestBody))
            .withPath(path), VerificationTimes.exactly(times));
    }

在我的测试中,我使用 RestTemplate 进行 API HTTP 调用。在一项测试中,此验证应通过:

CommonMockServerHelpers.verify("/save-file", "FAILED", 0);

另一方面,它不应该。 在运行测试时,它们会发生碰撞并导致彼此失败。 有没有办法为每个测试创建一些唯一性,以便我能够在不干扰其他测试的情况下验证测试的 MockServer 调用?

【问题讨论】:

    标签: spring-boot sessionid mockserver asynctest mockserver-netty


    【解决方案1】:

    你应该像这样在每个测试用例中写下期望:

    mockServerClientStorage.reset()
        .when(request()
                .withMethod("GET")
                .withPath("/save-file"))
        .respond(response()
                .withStatusCode(200)
                .withBody("Nice!"));
    
    mockServerClientStorage.reset()
        .when(request()
                .withMethod("GET")
                .withPath("/save-file"))
        .respond(response()
                .withStatusCode(500)
                .withBody("I failed!"));
    

    首先执行 reset() 很重要,因为这些期望由 mockServer 保存,否则会导致不稳定的测试。如果愿意,您可以在 @beforeEach 方法中执行 reset()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-06-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-10-05
      • 1970-01-01
      • 2015-09-23
      • 1970-01-01
      相关资源
      最近更新 更多