问题描述
我正在JUnit中使用Mockito,并且我有一种使用 RestTemplate 向微服务发出请求的方法.
I am using Mockito in JUnit and I have a method making a request to a microservice using RestTemplate.
private static final String REQUESTOR_API_HOST = "http://localhost:8090/requestor/v1/requestors/";
public TokenRequestorPayload getTokenRequestor(Long id) {
restClient = new RestTemplate();
return restClient.getForObject(REQUESTOR_API_HOST + id, TokenRequestorPayload.class);
}
此方法返回一个JSON对象,该对象将在TokenRequestorPayload类中反序列化.
This method returns a JSON object which will be deserialize in TokenRequestorPayload class.
当我执行单元测试时,它们由于模拟不起作用而失败,并且我得到了 org.springframework.web.client.ResourceAccessException .如何模拟我的RestTemplate?
When I execute unit tests they fail because mock didn't work and I got a org.springframework.web.client.ResourceAccessException. How can I mock my RestTemplate?
测试
RestTemplate restTemplate = Mockito.spy(RestTemplate.class);
Mockito.doReturn(this.tokenRequestorMockJson()).when(restTemplate).getForObject(Mockito.anyString(), Mockito.eq(TokenRequestorPayload.class));
错误
推荐答案
在您的测试中,您正在为RestTemplate的模拟实例定义行为,这很好.
In your test you are defining behavior for a mock instance of RestTemplate, which is good.
RestTemplate restTemplate = Mockito.spy(RestTemplate.class);
但是,被测类没有使用相同的实例,被测类每次都创建一个新的RestTemplate实例并使用该实例.
However, the same instance is not used by the Class Under Test which creates a new RestTemplate instance each time and uses that one.
public TokenRequestorPayload getTokenRequestor(Long id, RestTemplate restClient) {
restClient = new RestTemplate(); // it uses this instance, not the mock
return restClient.getForObject(REQUESTOR_API_HOST + id, TokenRequestorPayload.class);
}
因此,您需要找到一种将模拟实例带入getTokenRequestor()方法的方法.
So you need to find a way to bring the mock instance to the getTokenRequestor() method.
例如,这可以通过将restClient
转换为方法参数来实现:
E.g. this can be accomplished by turning restClient
into a method parameter:
public TokenRequestorPayload getTokenRequestor(Long id, RestTemplate restClient) {
return restClient.getForObject(REQUESTOR_API_HOST + id, TokenRequestorPayload.class);
}
,测试可能看起来像这样:
and the test might look something like like:
@Test
public void test() {
RestTemplate restTemplateMock = Mockito.spy(RestTemplate.class);
Mockito.doReturn(null).when(restTemplateMock).getForObject(Mockito.anyString(), Mockito.eq(TokenRequestorPayload.class));
// more code
instance.getTokenRequestor(id, restTemplateMock); // passing in the mock
}
这篇关于如何模拟REST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!