PHPUnit中传入桩方法的回调函数及关联受保护方法的测试实现
待测试的目标方法
public function performPoolRequest(RecreationRequestsCollection $requests): RecreatedPaymentsPoolReading { $count_request = count($requests); if($count_request) { $pool_recreate_payments = new RecreatedPaymentsPool(); $this->http_client->sendPoolRequest( $this->generateRequests($requests), $count_request, function (ResponseInterface $response, $index) use ($requests, $pool_recreate_payments) { $this->successHandler($response, $requests, $index, $pool_recreate_payments); }, function (BadResponseException $reason, $index) use ($requests, $pool_recreate_payments) { $this->failureHandler($reason, $requests, $index, $pool_recreate_payments); } ); return $pool_recreate_payments; } else { throw new PoolRequestException('Incorrect amount of requests: ' . $count_request); } }
测试实现的核心难点
在编写测试时,下述代码段的测试实现存在难点:
$this->http_client->sendPoolRequest( $this->generateRequests($requests), $count_request, function (ResponseInterface $response, $index) use ($requests, $pool_recreate_payments) { $this->successHandler($response, $requests, $index, $pool_recreate_payments); }, function (BadResponseException $reason, $index) use ($requests, $pool_recreate_payments) { $this->failureHandler($reason, $requests, $index, $pool_recreate_payments); } );
测试现状与目标
- 已完成
$this->http_client的Mock对象创建 - 存在问题:不清楚如何对传入
sendPoolRequest方法的各类参数开展测试,覆盖范围包括generateRequests($requests)的处理逻辑、successHandler、failureHandler的执行逻辑 - 已知可行方案:上述关联方法均为protected权限,可通过反射对象单独开展测试
- 预期探索方向:寻找可落地的实现方案,在单个测试用例中,通过校验最终返回的
$pool_recreate_payments对象中的值,完成上述关联逻辑的整体验证
内容的提问来源于stack exchange,提问作者Kirill Zaytsev
相关产品推荐
相关产品推荐

