mock resttemplate将服务测试为restFul客户端

时间:2016-07-04 11:18:44

标签: spring unit-testing spring-boot mockito

我有一个服务类,用spring编写,有一些方法。其中一个充当了一个宁静的消费者,如下所示:

.....
        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。我是否要创建一个静态类来将其注入我的服务中?

2 个答案:

答案 0 :(得分:6)

依赖注入的一个好处是能够轻松地模拟您的依赖项。在您的情况下,创建RestTemplate bean会更容易:

@Bean
public RestTemplate restTemplate() {
    return new RestTemplate();
}

而不是在您的客户端中使用new RestTemplate(),您应该使用:

@Autowired
private RestTemplate restTemplate;

对于使用Mockito进行单元测试,您必须模拟RestTemplate,例如使用:

@RunWith(MockitoJUnitRunner.class)
public class ClientTest {
    @InjectMocks
    private Client client;
    @Mock
    private RestTemplate restTemplate;
}

在这种情况下,Mockito将在RestTemplate中模拟并注入Client bean。如果你不喜欢通过反射进行模拟和注入,你总是可以使用单独的构造函数或setter来注入RestTemplate模拟。

现在你可以写一个这样的测试:

client.doStuff();
verify(restTemplate).exchange(anyString(), eq(HttpMethod.GET), any(HttpModel.class), eq(ReportModel.class));

你可能想要测试更多,但它给你一个基本的想法。

答案 1 :(得分:0)

您无法使用Mockito模拟restTemplate,因为实例是使用new关键字创建的。

相反,您应该尝试在测试类中创建一个模拟对象:

mock(RestTemplate.class)

并将其传递给服务类。

希望它有所帮助。

相关问题