假设我正在编写一个应用程序,我需要能够做到这样的事情:
String url = "https://someurl/";
GetMethod method = new GetMethod(URLEncoder.encode(url));
String content = method.getResponseBodyAsString();
Run Code Online (Sandbox Code Playgroud)
有没有办法提供一个模拟服务器让我处理https请求?我正在寻找的是一种编写单元测试的方法,但我需要能够模拟实际发布到https:// someurl的部分,这样我才能得到已知的响应.
看看 jadler ( http://jadler.net ),我一直在研究一个 http stubbing/mocking 库。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();
}
Run Code Online (Sandbox Code Playgroud)
您基本上有两个选择:
1. 抽象对框架的调用并进行测试。
例如,重构代码以允许您在某个时候注入模拟实现。有很多方法可以做到这一点。例如创建一个 getUrlAsString() 并模拟它。(上面也建议)。或者创建一个返回 GetMethod 对象的 url getter 工厂。然后工厂就可以被嘲笑了。
2. 启动应用程序服务器作为测试的一部分,然后针对它运行您的方法。(这将更多地是一个集成测试)
这可以通过多种方式实现。这可以是测试外部的,例如 maven jetty 插件。或者测试可以通过编程方式启动服务器。请参阅: http: //docs.codehaus.org/display/JETTY/Embedding+Jetty
通过 https 运行它会使事情变得复杂,但使用自签名证书仍然是可能的。但我会问自己 - 你到底想测试什么?我怀疑你是否真的需要测试 https 功能,它是一项经过验证的技术。
就我个人而言,我会选择选项 1 - 您正在尝试测试外部库的功能。这通常是不必要的。另外,将外部库的依赖关系抽象出来也是一个很好的做法。
希望这可以帮助。