简体   繁体   English

Wiremock:不使用UI的HTTP网站测试

[英]Wiremock: HTTP Web Site Testing without UI

我对如何在不使用UI的情况下测试HTTP网站提出了要求。可以说,我们有一个google网站搜索功能(不是Web服务),我需要对其进行测试。如何开始?任何人都可以举一些例子(JUnit)( Get / Post方法)来启动该项目。我尝试阅读官方文档,但未找到任何相关信息。

You can do it with the following snippet 您可以使用以下代码段进行操作

public class Searcher {

    public String search(String searchUrl, String searchWord) throws IOException, URISyntaxException {
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            URIBuilder builder = new URIBuilder(searchUrl);
            builder.setParameter("search_term", searchWord);

            HttpGet request = new HttpGet(builder.build());
            HttpResponse httpResponse = httpClient.execute(request);

            return convertResponseToString(httpResponse);
        }
    }

    private String convertResponseToString(HttpResponse response) throws IOException {
        try (Scanner scanner = new Scanner(response.getEntity().getContent(), "UTF-8")) {
            String responseString = scanner.useDelimiter("\\Z").next();

            return responseString;
        }
    }
}

public class SearcherTest {

    @Rule
    public WireMockRule wireMockRule = new WireMockRule(options().dynamicPort());

    @Test
    public void searchTest() throws IOException, URISyntaxException {
        String searchWord = "something";
        String expectedResult = "Your expected result";

        stubFor(get(urlPathEqualTo("/search"))
            .withQueryParam("search_term", equalTo(searchWord))
            .willReturn(aResponse()
                    .withBody(expectedResult)));

        Searcher searcher = new Searcher();
        String searchResult = searcher.search("http://localhost:" + wireMockRule.port() + "/search", searchWord);

        verify(getRequestedFor(urlPathEqualTo("/search"))
            .withQueryParam("search_term", equalTo(searchWord)));
        assertEquals(expectedResult, searchResult);
}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM