在我的Laravel项目中,我有一个服务类:
use GuzzleHttp\Client;
use App\Services\ApiService\Exceptions\ServiceException
class ApiService {
__construct(
protected Client $client
) {
}
public function request() {
try {
$response = $this->client->get('/test');
} catch (Exception $e) {
throw new ServiceException($e->getMessage(), $e->getCode(), $e);
}
return response;
}
}
我的自定义异常类ServiceException
如下所示:
class ServiceException extends Exception {
public function __construct($message, $code, $previous) {
parent::__construct($message, $code, $previous);
}
public function report() {
Log::error($this->getMessage());
}
}
并且我已经编写了一个测试用例,尝试验证当ApiService::request
抛出ServiceException
时,是否调用了Log::error
方法:
test_api_service_logs_error_when_request_fails() {
$clientMock = new Client([
'handler' => HandlerStack::create(
new MockHandler([
new Response(500, [], 'Internal Server Error')
])
)
]);
Log::shouldReceive('error')
->once()
$service = new ApiService($clientMock);
$service->request();
}
当我运行测试时,我得到了如下错误:
Method error() from Mockery_0_Illuminate_Log_LogManager should be called
据我理解,Laravel应该能够检测到ServiceException::report
方法并触发Log::error
调用,但目前看来并未如此。显然,在测试执行过程中和实际运行时Laravel的行为存在差异。如果有谁能帮我解答这个问题,将不胜感激!