Java 单元测试: HTTP --- WireMock

2019-03-27 15:39:25 浏览数 (1)

pom.xml增加依赖

代码语言:javascript复制
<dependency>
    <groupId>com.github.tomakehurst</groupId>
    <artifactId>wiremock</artifactId>
    <version>2.18.0</version>
    <scope>test</scope>
</dependency>

RemoteTest.java单元测试内容

代码语言:javascript复制
public class RemoteTest {
    @Rule
    public WireMockRule wireMockRule = new WireMockRule(8089);

    @Before
    public void setUp() {
        wireMockRule.resetAll();
        WireMock.stubFor(WireMock.get(WireMock.urlEqualTo("/my/resource"))
                .willReturn(WireMock.aResponse()
                        .withStatus(200)
                        .withBody("hello world!")));
    }

    @Test
    public void test() throws Exception {
        final OkHttpClient client = new OkHttpClient();
        final Request request = new Request.Builder()
                .url("http://localhost:8089/my/resource")
                .get().build();
        try(Response response = client.newCall(request).execute()) {
            final String content = response.body().string();
            Assert.assertEquals("hello world!", content);
        }
    }
}

注意事项

  1. WireMock启动后,实际上就是一个web服务器,也可以使用postman或浏览器直接访问(当然要保证WireMock没有退出,比如可以在测试用例中使用Thread.sleep(10000)
  2. 配置信息也可以统一写在文件中Stubbing

参考资料

  1. WireMock Getting Started
  2. Stubbing

如果对你有一点帮助,麻烦为我点一个赞,如果没有帮助,也非常期待你的反馈

0 人点赞