当它处理消息或代码以外的其他信息时,对抛出的异常执行任意断言可能很有用。
有没有比以下示例更简单、更易读或更"phpunit 推荐的方法"来做到这一点:
public function testTitleShouldNotAcceptArrayAsValue()
{
/* Arrange */
$schema = new schObjectSchema();
/* Expect */
$this->expectException(schException::class);
try {
/* Act */
$schema->title = [];
} catch (schException $exception) {
/* Assert */
$this->assertEquals('title', $exception->getProperty());
$this->assertEquals(
[
'properties' => [
'title' => [
'type' => 'string'
]
]
],
$exception->getRules()
);
throw $exception;
}
}
如果您要将其他信息放入异常对象中,并且想在测试中证明它正在设置,那么我会像您一样使用 try/catch。
IMO,expectException()
和重新throw
是多余的。在捕获结束时,我将通过传递返回函数,并且在捕获块失败($this->fail('schException was not thrown');
(之后,因为没有例外捕获,如计划的那样。
很明显,它正在做 - 而且在很多时候,清晰比优雅更有用。