java - 在java中模拟https请求

标签 java http mocking

假设我正在编写一个应用程序,我需要能够执行如下操作:

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/

相关文章:

java - HBase 表设计用于维护每个来源的每小时访客数量

跨平台 HTTP 服务器库

angular - @angular/common/http/testing TestRequest.flush 一个 boolean 值

unit-testing - 如何保持你的单元测试简单和隔离,同时仍然保证 DDD 不变量?

java - JPA 保存多个实体,在 Spring @Transactional 内部并启用 Exception.class 回滚时不会回滚

java - 如何更改使用 apachetiles 在 Spring 框架上编写的 html 页面的标题

Asp.Net Cors 在 OPTIONS 上返回 header ,但在 GET 请求上不返回

http - 如何倒带 io.ReadCloser

java - 相当于mockito中 spy 的Answers.RETURNS_DEEP_STUBS

java - 启动Android应用时阻塞GC Allocation问题的原因