Wiremock测试总是在一个简单的请求上获得404

时间:2016-05-16 20:53:03

标签: testing junit wiremock

我试图在单元测试中使用简单的请求让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;

}
}
}

1 个答案:

答案 0 :(得分: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

希望有所帮助!