junit Java:模拟Google API客户端库的HttpResponse

sulc1iza  于 2022-11-11  发布在  Java
关注(0)|答案(1)|浏览(146)

在寻找如何模拟http响应方面吃了很多苦头。模拟同一库的http请求很容易。我想在这里创建一个线程,如果你需要的话,可以保存你的时间。
需求-〉想要模拟在执行任何HttpRequest对象时返回的HttpResponse。(注意-这是专门针对google客户端API库的)

2vuwiymt

2vuwiymt1#

//creating mockContent for httpRequest
MockHttpContent mockHttpContent = new MockHttpContent();
String content = new String("requestBody");
mockHttpContent.setContent(str.getBytes());

//mocking httpResponse and linking to httpRequest's execution
HttpTransport transport =
        new MockHttpTransport() {
          @Override
          public LowLevelHttpRequest buildRequest(String method, String url) throws IOException {
            return new MockLowLevelHttpRequest() {
              @Override
              public LowLevelHttpResponse execute() throws IOException {
                MockLowLevelHttpResponse result = new MockLowLevelHttpResponse();
                result.setContent("responseBody");
                result.setContentEncoding("UTF-8");//this is very important
                result.setHeaderNames(List.of("header1","header2"));
                result.setHeaderValues(List.of("header1","header2"));
                return result;
              }
            };
          }
        };
HttpRequest httpRequest = transport.createRequestFactory().buildPostRequest(HttpTesting.SIMPLE_GENERIC_URL,mockHttpContent);

//getting httpResponse from httpRequest
 httpResponse = httpRequest.execute();

//condition to verify the content (body) of the response
assertEquals("responseBody",IOUtils.toString(httpResponse.getContent()));

相关问题