Examples
新建一个测试类HTTPRequestorMockTest
new 一个 WireMockService 配置一下 然后启动
wireMockServer = new WireMockServer(wireMockConfig().port(8090)); WireMock.configureFor("localhost", 8090); wireMockServer.start(); |
在测试方法之前
创建存根, 指明是GET方法,URL路径, Header的内容,会返回什么样的Response
@BeforeTest public void stubRequests() { stubFor(get(urlEqualTo("/cars/Chevy")) .withHeader("Accept", equalTo("application/json")) .withHeader("User-Agent", equalTo("Jakarta Commons-HttpClient/3.1")) .willReturn(aResponse() .withHeader("content-type", "application/json") .withStatus(200) .withBody("{\"message\":\"Chevy car response body\"}") ) ); } |
一切都模拟好了,接下来开始测试了,测试方法如下
@Test public void test_Get_Method() { String url = "http://localhost:8090/cars/Chevy"; String method = "GET"; String body = ""; HashMap<String, String> headers = new HashMap<String, String>(); headers.put("Accept", "application/json"); headers.put("User-Agent", "Jakarta Commons-HttpClient/3.1"); HTTPRequestor httpRequestor = new HTTPRequestor(); Response response = null; try { response = httpRequestor.perform_request(url, method, headers, body); } catch (Exception e) { fail("Problem using HTTPRequestor to generate response: " + e.getMessage()); } assertEquals(200, response.getStatusCode()); assertEquals("Chevy car response body", response.jsonPath().get("message")); } |
上面的例子是GET,没有请求体,下面我们来看POST的例子
同理 创建存根
RequestBody假设为"Mini Cooper"
stubFor(post(urlEqualTo("/cars/Mini")) .withHeader("Authorization", equalTo("Basic d8d74jf82o929d")) .withHeader("Accept", equalTo("application/json")) .withHeader("User-Agent", equalTo("Jakarta Commons-HttpClient/3.1")) .withRequestBody(equalTo("Mini Cooper")) .willReturn(aResponse() .withHeader("content-type", "application/json") .withStatus(200) .withBody("{\"message\":\"Mini Cooper car response body\", \"success\":true}") ) ); |
上文内容不用于商业目的,如涉及知识产权问题,请权利人联系博为峰小编(021-64471599-8017),我们将立即处理。