【问题标题】:How to use expectException in PHPUnit?如何在 PHPUnit 中使用 expectException?
【发布时间】:2020-08-01 10:16:11
【问题描述】:

我正在尝试测试我的异常,或 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.

可能是什么问题?

【问题讨论】:

  • 也来寻找这个问题的解决方案。我还没有找到任何很好的文档。如果我尝试 Pablo 的解决方案(看起来有效),我仍然会抛出异常。如果我将 expectException 放在 try-catch 的 catch 中,则会捕获到异常,但在我的测试运行期间它仍然会输出错误消息。

标签: php testing exception phpunit


【解决方案1】:

问题是永远不会抛出异常,因为您在 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');
    }
}

【讨论】:

    猜你喜欢
    • 2017-12-07
    • 2021-10-01
    • 2019-06-13
    • 1970-01-01
    • 1970-01-01
    • 2015-07-16
    • 1970-01-01
    • 1970-01-01
    • 2019-11-17
    相关资源
    最近更新 更多