Spock Mock在Lambda函数中失效问题求助
Spock Mock在CompletableFuture的Lambda中无法正常工作
问题场景
我尝试用Spock Mock RestTemplateAdapter,但在Lambda函数内部的CompletableFuture中无法正常生效。将retrieveProductListResponse改为public并直接从测试中调用时,Spock Mock能正常工作,因此怀疑问题与CompletableFuture内的Lambda执行有关。我已经把RestTemplate封装到适配器接口中,但问题依然存在。
测试代码
RestTemplateAdapter restTemplateAdapter = Mock(RestTemplateAdapter) int maxRety = 5 String baseUrl = "baseUrl" ProductRequestPort productRequestPort = new ProductRequestAdapter( restTemplateAdapter, baseUrl, maxRety) def "should throw error"() { given: String errorMsg = "Error test message" Long customerCode = 1234L when: productRequestPort.find(customerCode) then: maxRety * restTemplateAdapter.exchange(_, _, _, _) >> { throw new RuntimeException(errorMsg) } GatewayException error = thrown(GatewayException.class) error.getMessage() == "Error when trying to get products." }
待Mock的方法实现
public CompletableFuture<ProductListResponse> find(Long customerCode) { String url = BASE_URL + customerCode; HttpEntity<?> entity = new HttpEntity<>(); return CompletableFuture.supplyAsync(() -> { return retrieveProductListResponse(customerCode, url, entity); }); } private ProductListResponse retrieveProductListResponse(Long customerCode, String url, HttpEntity<?> entity) { int attempt = 0; while (attempt < MAX_RETRIES) { try { ResponseEntity<ProductListResponse> response = restTemplateAdapter.exchange( url, HttpMethod.GET, entity, ProductListResponse.class ); return response.getBody(); } catch (Exception e) { attempt++; } } throw new GatewayException(ERROR_GETTING_PRODUCTS); }
测试报错信息
Too few invocations for: maxRety * restTemplateAdapter.exchange(_, _, _, _) >> { throw new RuntimeException(errorMsg) } (1 invocation)
同时Mock的restTemplateAdapter返回null响应。
内容的提问来源于stack exchange,提问作者Myphre
相关产品推荐
相关产品推荐

