如何在 Java 中捕获 HTTP 请求并模拟其响应?

How to capture HTTP request and mock its response in Java?

假设 Java 应用程序向 http://www.google.com/... 发出请求并且无法配置继承的库(在内部发出此类请求),所以我无法存根或替换此 URL .

请分享一些创建模拟的最佳实践,例如

whenCalling("http://www.google.com/some/path").withMethod("GET").thenExpectResponse("HELLO")

因此,任何 HTTP 客户端对此 URL 发出的请求都将被重定向到模拟,并在当前 JVM 进程的上下文中用此响应替换 "HELLO"

我试图找到使用 WireMock、Mockito 或 Hoverfly 的解决方案,但它们似乎做了一些与此不同的事情。可能我只是没有正确使用它们。

你能展示一下 main 方法的简单设置吗:

  1. 创建模拟
  2. 开始模拟模拟
  3. 通过任意 HTTP 客户端(不与模拟库纠缠)向 URL 发出请求
  4. 收到模拟回复
  5. 停止模拟模拟
  6. 提出与第 3 步相同的请求
  7. 收到来自URL
  8. 的真实回复

以下是如何使用 API Simulator 实现您想要的效果。

该示例演示了将嵌入式 API 模拟器配置为 Spring 的 RestTemplate 客户端的 HTTP 代理的两种不同方法。查看(问题中的引述)"inherited library" 的文档 - 通常基于 Java 的客户端依赖于描述的系统属性 here 或者可能提供一些使用代码配置 HTTP 代理的方法。

package others;

import static com.apisimulator.embedded.SuchThat.*;
import static com.apisimulator.embedded.http.HttpApiSimulation.*;

import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Proxy.Type;
import java.net.URI;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.ClassRule;
import org.junit.Test;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import com.apisimulator.embedded.http.JUnitHttpApiSimulation;

public class EmbeddedSimulatorAsProxyTest
{

   // Configure an API simulation. This starts an instance of
   // Embedded API Simulator on localhost, default port 6090.
   // The instance is automatically stopped when the test ends.
   @ClassRule
   public static final JUnitHttpApiSimulation apiSimulation = JUnitHttpApiSimulation
         .as(httpApiSimulation("my-sim"));

   @BeforeClass
   public static void beforeClass()
   {
      // Configure simlets for the API simulation
      // @formatter:off
      apiSimulation.add(simlet("http-proxy")
         .when(httpRequest("CONNECT"))
         .then(httpResponse(200))
      );

      apiSimulation.add(simlet("test-google")
         .when(httpRequest()
               .whereMethod("GET")
               .whereUriPath(isEqualTo("/some/path"))
               .whereHeader("Host", contains("google.com"))
          )
         .then(httpResponse()
               .withStatus(200)
               .withHeader("Content-Type", "application/text")
               .withBody("HELLO")
          )
      );
      // @formatter:on
   }

   @Test
   public void test_using_system_properties() throws Exception
   {
      try
      {
         // Set these system properties just for this test
         System.setProperty("http.proxyHost", "localhost");
         System.setProperty("http.proxyPort", "6090");

         RestTemplate restTemplate = new RestTemplate();

         URI uri = new URI("http://www.google.com/some/path");
         ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);

         Assert.assertEquals(200, response.getStatusCode().value());
         Assert.assertEquals("HELLO", response.getBody());
      }
      finally
      {
         System.clearProperty("http.proxyHost");
         System.clearProperty("http.proxyPort");
      }
   }

   @Test
   public void test_using_java_net_proxy() throws Exception
   {
      SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory();

      // A way to configure API Simulator as HTTP proxy if the HTTP client supports it
      Proxy proxy = new Proxy(Type.HTTP, new InetSocketAddress("localhost", 6090));
      requestFactory.setProxy(proxy);

      RestTemplate restTemplate = new RestTemplate();
      restTemplate.setRequestFactory(requestFactory);

      URI uri = new URI("http://www.google.com/some/path");
      ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);

      Assert.assertEquals(200, response.getStatusCode().value());
      Assert.assertEquals("HELLO", response.getBody());
   }

   @Test
   public void test_direct_call() throws Exception
   {
      RestTemplate restTemplate = new RestTemplate();

      URI uri = new URI("http://www.google.com");
      ResponseEntity<String> response = restTemplate.getForEntity(uri, String.class);

      Assert.assertEquals(200, response.getStatusCode().value());
      Assert.assertTrue(response.getBody().startsWith("<!doctype html>"));
   }

}

使用 Maven 时,将以下内容添加到项目的 pom.xml 以将嵌入式 API 模拟器作为依赖项包含在内:

    <dependency>
      <groupId>com.apisimulator</groupId>
      <artifactId>apisimulator-http-embedded</artifactId>
      <version>1.6</version>
    </dependency>

... 这指向存储库:

  <repositories>
    <repository>
        <id>apisimulator-github-repo</id>
        <url>https://github.com/apimastery/APISimulator/raw/maven-repository</url>
     </repository>
  </repositories>