Spring Boot mockserver-netty测试不起作用

rbl8hiat  于 2022-11-23  发布在  Spring
关注(0)|答案(1)|浏览(177)

我尝试用mock-server开始一个简单的测试。我使用依赖关系:

testCompile group: 'org.mock-server', name: 'mockserver-netty', version: '5.6.1'

我已经从guide中选取了测试示例。我的测试非常简单:

public class MockServerTest {

private static ClientAndServer mockServer;

@BeforeClass
public static void startServer() {
    mockServer = startClientAndServer(1080);
}

private void simple() {
    new MockServerClient("127.0.0.1", 1080)
            .when(
                    request()
                            .withMethod("GET")
                            .withPath("/do"),
                    exactly(1)
            )
            .respond(
                    response()
                    .withStatusCode(200)
                            .withHeaders(
                                    new Header("Content-Type", "application/json; charset=utf-8"),
                                    new Header("Cache-Control", "public, max-age=86400"),
                                    new Header("Set-Cookie","SESSION=Njg1Mjg4NWQtZjRhOS00MDZhLWJhOGQtZmFmNWIzZjRmYTI4; Max-Age=1800; Expires=Wed, 4 Sep 2019 17:09:58 +0400; Path=/; HttpOnly; SameSite=Lax\n")
                            )

            .withDelay(TimeUnit.SECONDS,1)
            );
}

private org.apache.http.HttpResponse hitTheServerWithGetRequest(String page) {
    String url = "http://127.0.0.1:1080/"+page;
    HttpClient client = HttpClientBuilder.create().build();
    org.apache.http.HttpResponse response=null;
    HttpGet get = new HttpGet(url);
    try {
        response=client.execute(get);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }

    return response;
}

@Test
public void simpleTest() {
    simple();
    HttpResponse resp = hitTheServerWithGetRequest("do");

    new MockServerClient("localhost", 1080).verify(
            request()
                    .withMethod("GET")
                    .withPath("/do"),
            VerificationTimes.exactly(1)
    );
}

 @AfterClass
public static void stopServer() {
    mockServer.stop();
}
}

但是这个测试不起作用。它开始了,但从来没有完成。在我开始测试后,我可以用Postman做请求,我在控制台中看到日志,并获得响应-未找到(但必须是OK与指定的头)。我的代码与mockserver-netty有什么问题?

roejwanj

roejwanj1#

请尝试检查您的响应标头,预期的响应标头应该匹配,否则将返回错误404

相关问题