【问题标题】:Why does PHPUnit "receives" an Error object instead of an Exception object为什么 PHPUnit “接收”一个 Error 对象而不是 Exception 对象
【发布时间】:2019-09-06 09:35:55
【问题描述】:

当我测试一个使用 expectExceptionMessage('exception message') 引发异常的构造函数时,测试失败并且实际消息文本以“Class 'namespace\Class_Name'”为前缀。

它还指出抛出了一个 Error 类型的异常,而不是预期的 Exception 类型。

我是否错误地抛出了我的异常?

通过省略expectExceptionMessage 函数并将代码包含在try catch 语句中,我能够使测试通过。 这对我来说没有意义。

使用注释

/**
     * @expectedException        Exception
     * @expectedExceptionMessage no_file.json not found
     */

也没有解决问题。

PHPUnit测试代码:

public function testNonExistingFileInConstructor() {
        $this->expectException( 'Exception' );
        $this->expectExceptionMessage( 'no_file.json not found');
        new Json_File('no_file.json');
    }

抛出异常的代码:

public function __construct( $path_to_file ) {
        $json_file = file_get_contents( $path_to_file );
        if( false === $json_file ) {
            throw new Exception( $json_file . ' not found', 500 );
        }

        $data = json_decode( $json_file, true );
        if ( is_null( $data) ) {
            throw new Exception( 'invalid json in ' . $json_file, 600 );
        }

        $this->data = $data;
    }

【问题讨论】:

    标签: php phpunit


    【解决方案1】:

    Do not use annotations 期待异常。

    始终使用带有expectException() 的完全限定类名,例如$this->expectException(YourNamespace\Exception::class); 而不是$this->expectException('Exception');。 'Exception' 只是一个字符串,无法解析为您期望的异常的正确、完全限定名称。

    【讨论】:

    • 我确实在你关于为什么不使用注释的文章中看到了,我只是想看看它是否可以工作:) 我刚刚测试了它并且 ofc(因为我们欠你 PHPUnit)它可以工作!谢谢!只是为了我的理解,我看到 $this->expectExceptionMessage('my message') 现在在修复 $this->expectException 调用后也可以工作。这是否意味着expectExceptionMessage 函数依赖于传递给expectException 的正确类?再次感谢,不仅仅是答案,还有速度:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-30
    • 2012-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多