我正在使用 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对此几乎没有任何信息,我尝试寻找一些可以做到这一点的方法。
你尝试过吗
mockServerContainer.addExposedPorts(9999)
?