Как перехватить HTTP-запрос и смоделировать его ответ в Java? - PullRequest
1 голос
/ 17 марта 2020

Скажите, что Java приложение отправляет запросы на http://www.google.com/..., и нет никакой возможности настроить унаследованную библиотеку (делать такие запросы внутри), поэтому я не могу заглушить или заменить этот URL.

Пожалуйста, поделитесь некоторые рекомендации по созданию макета, такие как

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

, поэтому запрос любого HTTP-клиента на этот URL-адрес будет перенаправлен на макет и заменен этим ответом "HELLO" в контекст текущего процесса JVM.

Я пытался найти решение, используя WireMock, Mockito или Hoverfly, но кажется, что они делают что-то отличное от этого. Возможно, я просто не смог их правильно использовать.

Не могли бы вы показать простую настройку из метода main, например:

  1. create mock
  2. start mock simulation
  3. сделать запрос на URL произвольным HTTP-клиентом (не запутанным в библиотеку-насмешку)
  4. получить смоделированный ответ
  5. остановить симуляцию-имитацию
  6. сделать тот же запрос, что и на шаге 3
  7. получить реальный ответ с URL

1 Ответ

1 голос
/ 18 марта 2020

Вот как можно добиться того, чего вы хотите, с помощью API Simulator .

В этом примере демонстрируются два различных способа настройки встроенного API Simulator в качестве прокси-сервера HTTP для клиента RestTemplate Spring. Обратитесь к документации (цитата из вопроса) «унаследованной библиотеки» - часто клиенты, основанные на Java, полагаются на системные свойства, описанные здесь , или могут предложить какой-либо способ настройки 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>
...