php - PHPUnit:我应该在哪里抛出异常(expectException 方法)?
问题描述
我知道两个版本都是正确的,但我想知道哪个“更好”。方法的问题expectException()
在于它是在您键入启动异常的方法之前编写的。
我的问题是,我应该将它们放在方法的开头(以使它们更明显)还是仅在导致异常的方法之前(我认为它更有意义)?
- 选项 A)
/** @test */
public function shouldThrowsAnException(): void
{
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Error message');
$foo = new Foo();
$foo->bar(); // <-- This method launches the exception!!
}
- 选项 B)
/** @test */
public function shouldThrowsAnException(): void
{
$foo = new Foo();
$this->expectException(RuntimeException::class);
$this->expectExceptionMessage('Error message');
$foo->bar(); // <-- This method launches the exception!!
}
解决方案
在编写单元测试时,每个单元应该只测试一件事。因此,您expectException
应该尽可能具体,就像您在代码中所做的那样,寻找特定的异常和特定的消息。
如果您的构造函数碰巧抛出了相同的异常,那么选项 B 将是更好的选择,因此您不会意外捕获构造函数异常。如果构造函数确实抛出异常,那么您将编写其他测试用例来清除构造函数。
如果构造函数没有抛出任何异常,则两个单元测试在执行上是相同的。
如果您从可读性的角度询问,那么选项 B 更具可读性,因为很明显,期望您的方法Bar
将引发异常。
推荐阅读
- reactjs - 使用 JSX 内容反应轮播类型功能
- google-app-engine - App Engine 的设置中不显示每日支出限制选项
- c# - 如何转换 IEnumerable
到 C# 中的字节 []? - email - 电子邮件 550 5.4.1 从 Sendgrid 到 Outlook 的访问被拒绝
- javascript - 为什么这是“你好,世界!” JavaScript 代码片段被识别为可接受的程序指令?
- c - 重复代码的分离 - common.h 文件 - 使用自定义参数声明函数
- linux-kernel - 是否可以使用 RARP 在 uboot 中传输文件?
- vba - 删除两个文件夹上的标志状态
- sql - SQL Calculating Median per Product in Cursor
- c++ - std::map, std::unordered_map - 在初始化列表中缩小转换