我想用 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
}
}
添加一些换行符以避免水平滚动并揭示主要问题:
then:
1 * restTemplate
.getForEntity("http://localhost:8080/products", Product.class)
.getBody()
>> product
链式方法调用对于模拟来说是无效的语法。第二个方法调用是在第一个方法返回的
ResponseEntity
上,但您没有模拟该方法。