首页 > 解决方案 > PHPUnit:我应该在哪里抛出异常(expectException 方法)?

问题描述

我知道两个版本都是正确的,但我想知道哪个“更好”。方法的问题expectException()在于它是在您键入启动异常的方法之前编写的。

我的问题是,我应该将它们放在方法的开头(以使它们更明显)还是仅在导致异常的方法之前(我认为它更有意义)?

/** @test */
public function shouldThrowsAnException(): void
{
    $this->expectException(RuntimeException::class);
    $this->expectExceptionMessage('Error message');

    $foo = new Foo();
    $foo->bar(); // <-- This method launches the exception!!
}
/** @test */
public function shouldThrowsAnException(): void
{
    $foo = new Foo();

    $this->expectException(RuntimeException::class);
    $this->expectExceptionMessage('Error message');
    $foo->bar(); // <-- This method launches the exception!!
}

标签: phpphpunit

解决方案


在编写单元测试时,每个单元应该只测试一件事。因此,您expectException应该尽可能具体,就像您在代码中所做的那样,寻找特定的异常和特定的消息。

如果您的构造函数碰巧抛出了相同的异常,那么选项 B 将是更好的选择,因此您不会意外捕获构造函数异常。如果构造函数确实抛出异常,那么您将编写其他测试用例来清除构造函数。

如果构造函数没有抛出任何异常,则两个单元测试在执行上是相同的。

如果您从可读性的角度询问,那么选项 B 更具可读性,因为很明显,期望您的方法Bar将引发异常。


推荐阅读