假设我正在编写一个应用程序,我需要能够执行如下操作:
String url = "https://someurl/";
GetMethod method = new GetMethod(URLEncoder.encode(url));
String content = method.getResponseBodyAsString();
有没有办法提供一个模拟服务器来让我处理 https 请求?我正在寻找的是一种编写单元测试的方法,但我需要能够模拟实际输出到 https://someurl 的部分。这样我就能得到已知的回复。
最佳答案
看看 jadler ( http://jadler.net ),一个我已经研究了一段时间的 http stub /模拟库。 1.0.0 稳定版刚刚发布,它应该提供你所要求的能力:
@Test
public void getAccount() {
onRequest()
.havingMethodEqualTo("GET")
.havingURIEqualTo("/accounts/1")
.havingBody(isEmptyOrNullString())
.havingHeaderEqualTo("Accept", "application/json")
.respond()
.withTimeout(2, SECONDS)
.withStatus(200)
.withBody("{\"account\":{\"id\" : 1}}")
.withEncoding(Charset.forName("UTF-8"))
.withContentType("application/json; charset=UTF-8");
final AccountService service = new AccountServiceRestImpl("http", "localhost", port());
final Account account = service.getAccount(1);
assertThat(account, is(notNullValue()));
assertThat(account.getId(), is(1));
}
@Test
public void deleteAccount() {
onRequest()
.havingMethodEqualTo("DELETE")
.havingPathEqualTo("/accounts/1")
.respond()
.withStatus(204);
final AccountService service = new AccountServiceRestImpl("http", "localhost", port());
service.deleteAccount(1);
verifyThatRequest()
.havingMethodEqualTo("DELETE")
.havingPathEqualTo("/accounts/1")
.receivedOnce();
}
关于java - 在java中模拟https请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3857776/