【问题标题】:How to mock rest client inside a Spring boot integration test如何在 Spring Boot 集成测试中模拟 rest 客户端
【发布时间】:2017-12-05 12:39:34
【问题描述】:

在使用 @SpringBootTest 注释并使用 @RunWith(SpringRunner.class) 运行的 Spring Boot 集成测试中,我可以通过 @Autowired TestRestTemplate restTemplaterestTemplate.postForEntity(...) 将真正的 http post 调用丢弃到我的 rest 控制器

这很好用,就在控制器的末尾 -> 服务 -> restclient 链我有一个休息客户端 bean,它使用内部的 RestTemplates 调用第 3 方休息端点,所以我必须模拟这个端点。我找到了这个库com.github.tomakehurst.wiremock.client.WireMock,它可以用于这个,但是想知道是否没有一个很好的spring boot方式,比如用@RestClientTest测试一个rest客户端来实现这个。我试图模拟MockRestServiceServer,以便我可以在上面写expectations and responses,但它似乎没有得到它。我的 REST 客户端中的 REST 模板始终创建为真实模板,因此我对第 3 方端点的调用失败。

【问题讨论】:

  • 您可以使用@MockBean(参见例如docs.spring.io/spring-boot/docs/current/reference/html/…)作为RestTemplate,但我认为wiremock 是更合适的抽象级别,对重构您如何调用这些端点的方式更具弹性。
  • @MockBean 在 rest 模板上也不能正常工作。它只是不模拟其余客户端 bean 中的模板
  • 另一种方式,您可以将 Spy 用于服务并仅模拟休息调用。有时为此目的,我在服务中创建方法,例如:public Client getRestClient(),我将其用于未来的间谍活动。
  • 好吧,也许是一种可能的方式,但在我看来,这就像一个 hack,而不是真正准备好的 Spring Boot 解决方案。在这种情况下,我宁愿选择wiremock
  • 只需将@MockBean 用于RestClient 而不是RestTemplate?!

标签: spring-boot integration-testing resttemplate wiremock


【解决方案1】:

您可以使用ReflectionTestUtils@Before 中注入模拟

@Inject
private Service service;

@Mock
private RestClient restClient;

@Before
public void setup() {
    ReflectionTestUtils.setField(service, "restClient", restClient);
}

【讨论】:

  • 谢谢,但反射似乎不是一个没有破解的解决方案。也许没有弹簧靴的方式,他们可以改进这一点
  • 如果您不喜欢反射,也可以创建和使用 setter。
  • 谢谢,其实我追求的是一个好的设计,而不仅仅是一种可能性。仅仅为了测试而添加 setter 是不可取的。
猜你喜欢
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
  • 2015-08-31
  • 2021-04-16
  • 2020-08-08
  • 2013-10-23
  • 2018-05-12
  • 2021-04-09
相关资源
最近更新 更多