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 关注
- 105 浏览
添加回答
举报