PHPUnit try catch 在测试用例中不起作用

标签 php exception phpunit

我试图在 PHPUnit 测试中捕获异常,但它没有按预期工作。异常似乎在更高级别被捕获,我不明白为什么。

public function testException()
    {
        echo 'Enter';
        try {
            throw new Exception('error.');
        } catch (Exception $e) {
            echo 'catch Exception';
        }
        echo 'End';
    }

在输出中只有“Enter”可见。我没有到达“终点”。 (我使用的是 PHP7)

谢谢

编辑: 用 \Exception 替换所有 Exception 解决了我的问题

最佳答案

处理异常可能很棘手,尤其是当它们被称为 Exception :-)

看看所有的反馈this (almost the same) question已生成。

现在,只有与预期的类不匹配时才捕获异常。在这种情况下,肯定是因为不精确的 Exception 类名规范,这肯定会通过将它们指定为 \Exception 来解决。

正如上述问题线程中的评论者巧妙地指出的那样:

Without the backslash Exception is specific to the namespace and won't be matched (or caught).

关于PHPUnit try catch 在测试用例中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39277421/

相关文章:

java - Java 中的 try-catch 和循环异常

php - 如何在测试中加载表单类型

php - 无法使用 Xampp 加载 Zend 加载程序

php - 如何从jquery到PHP获取输入值1乘1

php - 这是 json 以及如何用 php 变量替换值?

Php 文件内容到多个表

php - PHP 中内置了哪些异常子类?

exception - 如何在Dart中调用addIceCandidate

php - @group 注释可以在 phpunit 的类级别上使用吗

php - 使用 DataFixtures 在 WebTestCase 上执行 phpUnitTest 后拆卸数据库