1

我试图让wiremock在我的单元测试中通过一个简单的请求返回一个200状态,但是,这个单元测试总是返回一个404错误。

如何解决?

import static com.github.tomakehurst.wiremock.client.WireMock.*;
import static org.junit.Assert.assertTrue;

import com.github.tomakehurst.wiremock.junit.WireMockRule;
import org.junit.Rule;
import org.junit.Test;

import java.net.HttpURLConnection;
import java.net.URL;

public class WiremockTest {

@Rule
public WireMockRule wireMockRule = new WireMockRule(8089); // No-args constructor defaults to port 8080

@Test
public void exampleTest() throws Exception {
    stubFor(get(urlPathMatching("/my/resource[0-9]+"))
            .willReturn(aResponse()
                    .withStatus(200)
                    .withHeader("Content-Type", "text/xml")
                    .withBody("<response>Some content</response>")));

    int result = sendGet("http://localhost/my/resource/121");
    assertTrue(200 == result);

    //verify(getRequestedFor(urlMatching("/my/resource/[a-z0-9]+")));
}

private int sendGet(String url) throws Exception {
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();

    // optional default is GET
    con.setRequestMethod("GET");

    int responseCode = con.getResponseCode();
    return responseCode;

}
}
}
4

1 回答 1

1

使用您提供的代码,我首先必须处理被抛出的java.net.ConnectionException 。您的测试 url 需要 localhost 上的端口。 sendGet("http://localhost:8089/my/resource/121")

之后,我认为您获得 404 的原因是您的正则表达式与您的测试网址不匹配。

urlPathMatching("/my/resource[0-9]+")

应该

urlPathMatching("/my/resource/[0-9]+")

注意 'resource' 和 '[0-9]+' 之间的附加路径分隔符

用于正则表达式测试的在线工具(如regex101)可用于测试模式匹配行为。(记得避开你的正斜杠)

图案 :\/my\/resource\/[0-9]+

测试字符串:http://localhost:8089/my/resource/121

希望有帮助!

于 2016-05-17T01:06:32.463 回答