【问题标题】:mock resttemplate to test a service as restFul client模拟 resttemplate 以测试服务作为 restFul 客户端
【发布时间】:2016-11-06 02:39:07
【问题描述】:

我有一个服务类,用 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。我必须创建一个静态类来将其注入到我的服务中?

【问题讨论】:

  • 您使用哪个模拟框架?此外,如果您可以使用依赖注入来注入 RestTemplate 而不是创建一个新的 RestTemplate,这将轻松很多

标签: spring unit-testing spring-boot mockito


【解决方案1】:

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

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

mock(RestTemplate.class)

并将其传递给服务类。

希望对您有所帮助。

【讨论】:

  • 我必须使用一个静态类来实例化一个restTemplate并注入它?
  • 我宁愿添加字段来存储restTemplate 并创建包可见的构造函数来注入模拟。
【解决方案2】:

依赖注入的好处之一是能够轻松地模拟你的依赖。在您的情况下,创建 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 bean 注入您的Client。如果您不喜欢通过反射进行模拟和注入,您可以随时使用单独的构造函数或设置器来注入 RestTemplate 模拟。

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

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

你可能想要测试的不止这些,但它会给你一个基本的想法。

【讨论】:

  • 是的,就是这样!非常感谢
猜你喜欢
  • 2016-07-17
  • 2013-10-23
  • 2015-10-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
相关资源
最近更新 更多