我有一个服务类,用春天写的,有一些方法.其中一个充当了如下的宁静消费者:
.....
HttpEntity request = new HttpEntity<>(getHeadersForRequest());
RestTemplate restTemplate = new RestTemplate();
String url = ENDPOINT_URL.concat(ENDPOINT_API1);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(url)
.queryParam("param1",parameter1);
ReportModel infoModel = null;
try{
infoModel = restTemplate.exchange(builder.toUriString(),HttpMethod.GET,request,ReportModel.class).getBody();
}catch (HttpClientErrorException | HttpServerErrorException e){
e.printStackTrace();
}
我想使用Mockito来模拟我的服务,但是每个与restful服务器实例交互的方法都是一个新的RestTemplate.我要创建一个静态类来将它注入我的服务中?
最佳答案
依赖注入的一个好处是能够轻松地模拟您的依赖项.在您的情况下,创建RestTemplate bean会容易得多:
@Bean
public RestTemplate restTemplate() {
return new RestTemplate();
}
而不是在您的客户端使用新的RestTemplate(),你应该使用:
@Autowired
private RestTemplate restTemplate;
对于使用Mockito进行单元测试,您必须模拟RestTemplate,例如使用:
@RunWith(MockitoJUnitRunner.class)
public class ClientTest {
@InjectMocks
private Client client;
@Mock
private RestTemplate restTemplate;
}
在这种情况下,Mockito将在您的客户端中模拟并注入RestTemplate bean.如果您不喜欢通过反射进行模拟和注入,则可以始终使用单独的构造函数或setter来注入RestTemplate模拟.
现在您可以编写如下测试:
client.doStuff();
verify(restTemplate).exchange(anyString(),eq(HttpMethod.GET),any(HttpModel.class),eq(ReportModel.class));
你可能想要测试更多,但它给你一个基本的想法.
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。