【问题标题】:Better solution to do arbitrary assertions on an expected exception?对预期异常进行任意断言的更好解决方案?
【发布时间】:2018-01-19 08:53:35
【问题描述】:

在处理消息或代码以外的其他信息时,对抛出的异常执行任意断言可能很有用。

是否有比以下示例更简单、可读或更“phpunit 推荐的方式”来做到这一点:

public function testTitleShouldNotAcceptArrayAsValue()
{
    /* Arrange */
    $schema = new sch\ObjectSchema();


    /* Expect */
    $this->expectException(sch\Exception::class);


    try {
        /* Act */
        $schema->title = [];
    } catch (sch\Exception $exception) {
        /* Assert */
        $this->assertEquals('title', $exception->getProperty());
        $this->assertEquals(
            [
                'properties' => [
                    'title' => [
                        'type' => 'string'
                    ]
                ]
            ],
            $exception->getRules()
        );
        throw $exception;
    }
}

【问题讨论】:

    标签: php unit-testing exception phpunit


    【解决方案1】:

    如果您将附加信息放入异常对象中,并希望在测试中证明它已被设置,那么我会像您一样使用 try/catch。

    IMO,expectException() 和 re-throw 是多余的。在 catch 结束时,我将通过 pass 从函数中返回,并且在 catch 块失败后(使用 $this->fail('sch\Exception was not thrown');),因为没有要捕获的异常,正如计划的那样。

    这是完全显而易见的——在很多时候,清晰比优雅更有用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多