[英]How to use expectException in PHPUnit?
我正在尝试测试我的异常,或 PHP 单元中的任何其他异常。
<?php declare(strict_types=1);
namespace Tests\Exception;
use PHPUnit\Framework\TestCase;
class DrinkIsInvalidExceptionTest extends TestCase
{
public function testIsExceptionThrown(): void
{
$this->expectException(\Exception::class);
try {
throw new \Exception('Wrong exception');
} catch(\Exception $exception) {
echo $exception->getCode();
}
}
}
仍然失败:
Failed asserting that exception of type "Exception" is thrown.
可能是什么问题呢?
问题是永远不会抛出异常,因为您在 catch 块中捕获它。 测试您的异常的正确代码是这样的:
class DrinkIsInvalidExceptionTest extends TestCase
{
public function testIsExceptionThrown(): void
{
$this->expectException(\Exception::class);
$this->expectExceptionCode('the_expected_code');
$this->expectExceptionMessage('Wrong exception');
// Here the method that throws the exception
throw new \Exception('Wrong exception');
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.