如何在Spring启动集成测试中模拟rest客户端

时间:2017-12-05 12:39:35

标签: spring-boot integration-testing resttemplate wiremock

在使用@SpringBootTest注释并使用@RunWith(SpringRunner.class)进行注释的春季启动集成测试中,我可以通过@Autowired TestRestTemplate restTemplaterestTemplate.postForEntity(...)

这很好,只是在控制器的末尾 - >服务 - > restclient链我有一个rest客户端bean,它使用RestTemplates调用第三方休息端点,所以我必须模拟这个端点。我找到了这个lib com.github.tomakehurst.wiremock.client.WireMock,它可以用于此,但是想知道是否有一个不错的弹簧启动方式,例如用@RestClientTest来测试一个休息客户端来实现这个目的。我试图模仿MockRestServiceServer,以便我可以在上面写expectations and responses,但它似乎没有得到它。我的休息客户端中的其余模板始终是真实的,因此我对第三方端点的调用失败。

1 个答案:

答案 0 :(得分:0)

您可以使用ReflectionTestUtils

@Before中注入模拟
@Inject
private Service service;

@Mock
private RestClient restClient;

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