如何使用 Spock 进行模拟

问题描述 投票:0回答:1

我想用 Spock 模拟 Spring ResTemplate 的 getEntity 方法

Product getProducts(ProductSearch request) {
  Map<String, Object> queryParam = new HashMap<>();
  queryParam.put("id", request.getProductId());
  queryParam.put("category", request.getCategory());

  UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromHttpUrl(url);
  queryParam.forEach(uriComponentsBuilder::queryParam);

  String url = uriComponentsBuilder.toUriString();
  return restTemplate.getForEntity(url, Product.class).getBody();
}

我面临的问题是如何模拟 getBody() 部分。我尝试了这个并得到了 NullPointerException

class ProductClientSpec extends Specification {
  RestTemplate restTemplate = Mock()
  ProductClient legacyOpenSlotsClient = new ProductClient(restTemplate)

  def setup() {}

  def 'should return product'() {
    given:
    ProductSearch request = createProductRequest()
    Product product = createProductResponse()

    when:
    ProductClient.getProducts(request)

    then:
    1 * restTemplate.getForEntity("http://localhost:8080/products", Product.class).getBody() >> product
  }
}
unit-testing groovy spock
1个回答
0
投票

添加一些换行符以避免水平滚动并揭示主要问题:

then:
  1 * restTemplate
    .getForEntity("http://localhost:8080/products", Product.class)
    .getBody()
  >> product

链式方法调用对于模拟来说是无效的语法。第二个方法调用是在第一个方法返回的

ResponseEntity
上,但您没有模拟该方法。

© www.soinside.com 2019 - 2024. All rights reserved.