如何在PHPUnit中使用expectException?

Grz*_*zak 7 php testing phpunit exception

我正在尝试测试我的异常,或 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();
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

仍然失败:

Failed asserting that exception of type "Exception" is thrown.
Run Code Online (Sandbox Code Playgroud)

可能是什么问题呢?

小智 16

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