如何使用spring-cloud-netflix和feign编写集成测试 [英] How to write integration tests with spring-cloud-netflix and feign
问题描述
我使用Spring-Cloud-Netflix在微服务之间进行通信.假设我有两个服务,即Foo和Bar,而Foo使用了Bar的REST端点之一.我使用带有@FeignClient
注释的接口:
I use Spring-Cloud-Netflix for communication between micro services. Let's say I have two services, Foo and Bar, and Foo consumes one of Bar's REST endpoints. I use an interface annotated with @FeignClient
:
@FeignClient
public interface BarClient {
@RequestMapping(value = "/some/url", method = "POST")
void bazzle(@RequestBody BazzleRequest);
}
然后我在Foo中有一个服务类SomeService
,它调用了BarClient
.
Then I have a service class SomeService
in Foo, which calls the 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
.
Now, to make sure the communication between services works, I want to build a test that fires a real HTTP request against a fake Bar server, using something like WireMock. The test should make sure that feign correctly decodes the service response and reports it to 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中,这样假装就能找到它并与之通信?我需要哪种注释魔术?
How can I inject such a WireMock server into eureka, so that feign is able to find it and communicate with it? What kind of annotation magic do I need?
推荐答案
使用Spring的RestTemplate代替伪装. RestTemplate还能够通过eureka解析服务名称,因此您可以执行以下操作:
Use Spring's RestTemplate instead of feign. RestTemplate is also able to resolve service names via eureka, so you can do something like this:
@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进行测试比伪装更容易.
This is way easier testable with Wiremock than feign.
这篇关于如何使用spring-cloud-netflix和feign编写集成测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!