温馨提示:本文翻译自stackoverflow.com,查看原文请点击:java - How to write integration tests with spring-cloud-netflix and feign
java netflix-eureka spring-cloud-netflix wiremock feign

java - 如何使用spring-cloud-netflix和feign编写集成测试

发布于 2020-04-16 16:04:17

我使用Spring-Cloud-Netflix在微服务之间进行通信。假设我有两个服务,Foo和Bar,而Foo使用Bar的REST端点之一。我使用带有以下注释的接口@FeignClient

@FeignClient
public interface BarClient {
  @RequestMapping(value = "/some/url", method = "POST")
  void bazzle(@RequestBody BazzleRequest);
}

然后,我SomeService在Foo中有一个服务类,称为BarClient

@Component
public class SomeService {
    @Autowired
    BarClient barClient;

    public String doSomething() {
      try {
        barClient.bazzle(new BazzleRequest(...));
        return "so bazzle my eyes dazzle";
      } catch(FeignException e) {
        return "Not bazzle today!";
      }

    }
}

现在,为了确保服务之间的通信正常,我想构建一个测试,使用WireMock之类的东西向伪造的Bar服务器触发真实的HTTP请求。测试应确保伪装正确解码服务响应并将其报告给SomeService

public class SomeServiceIntegrationTest {

    @Autowired SomeService someService;

    @Test
    public void shouldSucceed() {
      stubFor(get(urlEqualTo("/some/url"))
        .willReturn(aResponse()
            .withStatus(204);

      String result = someService.doSomething();

      assertThat(result, is("so bazzle my eyes dazzle"));
    }

    @Test
    public void shouldFail() {
      stubFor(get(urlEqualTo("/some/url"))
        .willReturn(aResponse()
            .withStatus(404);

      String result = someService.doSomething();

      assertThat(result, is("Not bazzle today!"));
    }
}

我如何将这样的WireMock服务器注入eureka,以便让feign能够找到它并与之通信?我需要哪种注释魔术?

查看更多

提问者
Bastian Voigt
被浏览
30
Bastian Voigt 2017-02-03 13:13

使用Spring的RestTemplate代替伪装。RestTemplate还能够通过eureka解析服务名称,因此您可以执行以下操作:

@Component
public class SomeService {
   @Autowired
   RestTemplate restTemplate;

   public String doSomething() {
     try {
       restTemplate.postForEntity("http://my-service/some/url", 
                                  new BazzleRequest(...), 
                                  Void.class);
       return "so bazzle my eyes dazzle";
     } catch(HttpStatusCodeException e) {
       return "Not bazzle today!";
     }
   }
}

使用Wiremock比伪装更容易测试。