1 回答

TA貢獻1825條經驗 獲得超4個贊
得到這個工作。斷言在測試用例期間拋出并記錄異常。
測試與此類似的場景
<?php
class Service
{
/**
* @var \Psr\Log\LoggerInterface
*/
protected $logger;
public function setLogger(\Psr\Log\LoggerInterface $logger)
{
$this->logger = $logger;
}
public function doSomething($value)
{
try {
$this->handleDoingSomething($value);
}
catch (Exception $e) {
$this->logger->error($e->getMessage());
// or optionally
$this->logger->log(\Psr\Log\LogLevel::ERROR, $e->getMessage());
throw $e;
}
}
protected function handleDoingSomething($value)
{
throw new Exception();
}
}
可以通過使用這樣的測試用例來實現
<?php
class ServiceTest extends \PHPUnit\Framework\TestCase
{
public function testDoSomething()
{
$loggerCalledCount = 0;
$loggerCallback = function ($methodParameter) use (&$loggerCalledCount) {
$loggerCalledCount++;
return true;
};
$logger = $this->createMock(\Psr\Log\LoggerInterface::class);
$logger->method('error')->with($this->callback($loggerCallback));
$logger->method('log')->with(\Psr\Log\LogLevel::ERROR, $this->callback($loggerCallback));
$exceptionCaught = false;
try {
$service = new Service();
$value = 'this value will trigger an exception if used';
$service->doSomething($value);
}
catch (Exception $e) {
$exceptionCaught = true;
}
$this->assertTrue($exceptionCaught);
$this->assertGreaterThan(0, $loggerCalledCount);
}
}
希望能幫助人們。
- 1 回答
- 0 關注
- 126 瀏覽
添加回答
舉報