PHPUnit try catch 在测试用例中不起作用
PHPUnit try catch does not work in a test case
我试图在 PHPUnit 测试中捕获异常,但它没有像我预期的那样工作。异常似乎是在更高层捕获的,我不明白为什么。
public function testException()
{
echo 'Enter';
try {
throw new Exception('error.');
} catch (Exception $e) {
echo 'catch Exception';
}
echo 'End';
}
在输出中只有 'Enter' 可见。我没有达到'End'。
(我正在使用 PHP7)
谢谢
编辑:
用 \Exception
替换所有 Exception
解决了我的问题
处理异常可能很棘手,尤其是当它们被调用时 Exception
:-)
看看 this (almost the same) question 产生的所有反馈。
现在,只有在与预期不匹配时才会捕获异常 class。在这种情况下,肯定是因为不精确的 Exception
class 名称规范,这肯定会通过将它们指定为 \Exception
.
来解决
正如来自上述问题线程的评论者巧妙地指出的那样:
Without the backslash Exception is specific to the namespace and won't be matched (or caught).
我试图在 PHPUnit 测试中捕获异常,但它没有像我预期的那样工作。异常似乎是在更高层捕获的,我不明白为什么。
public function testException()
{
echo 'Enter';
try {
throw new Exception('error.');
} catch (Exception $e) {
echo 'catch Exception';
}
echo 'End';
}
在输出中只有 'Enter' 可见。我没有达到'End'。 (我正在使用 PHP7)
谢谢
编辑:
用 \Exception
替换所有 Exception
解决了我的问题
处理异常可能很棘手,尤其是当它们被调用时 Exception
:-)
看看 this (almost the same) question 产生的所有反馈。
现在,只有在与预期不匹配时才会捕获异常 class。在这种情况下,肯定是因为不精确的 Exception
class 名称规范,这肯定会通过将它们指定为 \Exception
.
正如来自上述问题线程的评论者巧妙地指出的那样:
Without the backslash Exception is specific to the namespace and won't be matched (or caught).