pom.xml增加依赖
com.github.tomakehurst
wiremock
2.18.0
test
RemoteTest.java单元测试内容
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);
}
}
}
注意事项
WireMock启动后,实际上就是一个web服务器,也可以使用postman或浏览器直接访问(当然要保证WireMock没有退出,比如可以在测试用例中使用Thread.sleep(10000)
配置信息也可以统一写在文件中Stubbing
参考资料
如果对你有一点帮助,麻烦为我点一个赞,如果没有帮助,也非常期待你的反馈