使用测试容器对模拟服务器的端口号进行哈编码

问题描述 投票:0回答:1

我正在使用 testcontainers 在 JUnit5 中创建一个模拟服务器。 看来每次运行的端口号都是随机变化的,我希望它有一个固定的端口号,我将决定。 如何做到这一点?

import kong.unirest.ContentType;
import kong.unirest.HttpStatus;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Tag;
import org.junit.jupiter.api.Test;
import org.mockserver.client.MockServerClient;
import org.mockserver.model.HttpResponse;
import org.mockserver.model.HttpStatusCode;
import org.testcontainers.containers.MockServerContainer;
import org.testcontainers.junit.jupiter.Container;
import org.testcontainers.junit.jupiter.Testcontainers;
import org.testcontainers.shaded.com.google.common.net.HttpHeaders;
import org.testcontainers.utility.DockerImageName;

import java.nio.file.Path;
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockserver.model.HttpRequest.request;


@Testcontainers
class Mocking {

    @Container
    private static final MockServerContainer mockServerContainer = new MockServerContainer(
            DockerImageName.parse("mockserver/mockserver"));
    private static MockServerClient mockServerClient;
    private static String BASE_URL;


    @BeforeAll
    public static void initialize() {
        mockServerClient = new MockServerClient(mockServerContainer.getHost(), mockServerContainer.getServerPort());
        BASE_URL = mockServerContainer.getEndpoint();
        System.out.println(BASE_URL);// its printing localhost:portnumber
        //the portnumber is random for each run, I want it to be consistent
    }

    @BeforeEach
    public void setup() {
        mockServerClient.reset();
    }


    @Test
    void helloWorldTest() {
        Map<String, String> headers = Map.of(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType());

        String expectedResponse = JsonHelper.toJsonString("Hello World!");

        mockServerClient
                .when(request().withMethod("GET")
                        .withHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType())
                )
                .respond(HttpResponse.response()
                        .withHeader(HttpHeaders.CONTENT_TYPE, ContentType.APPLICATION_JSON.getMimeType())
                        .withStatusCode(HttpStatusCode.OK_200.code())
                        .withBody(expectedResponse)
                );

        Response response = HttpUtil.builder().baseUrl(BASE_URL).headers(headers).build().get(null).call();
        assertThat(response.getStatus()).isEqualTo(HttpStatus.OK);
        assertThat(response.asString()).isEqualTo(expectedResponse);
    }


}

官方文档JavaDoc对此几乎没有任何信息,我尝试寻找一些可以做到这一点的方法。

java junit5 testcontainers
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.