如何使用 PHPunit 检查 Exception 属性

问题描述 投票:0回答:2

我有以下例外:

<?php
namespace App\Exception;

class LimitReachedException extends \Exception
{
    private ?\DateTime $resumeAt;

    ...getter/setter..
}

我的 PHPUnit 像这样检查此异常:

$this->expectException(LimitReachedException::class);

如何检查某个值是否也存储在

$resumeAt
属性中?

symfony phpunit
2个回答
0
投票

尽管 PHPUnit 有一个允许传递异常实例的

expectExceptionObject
方法,但这只是
expectExceptionMessage
expectException
expectExceptionCode
的快捷方式。

目前实现断言的一种方法(PHPUnit 的当前版本为 9.5.27)是不使用 PHPUnit 预期异常的方法,而是自己捕获它,然后断言不同的属性:

function testException () {
    $expectedException = null;
    try {
        $foo->doSomething();
    } catch (LimitReachedException $e) {
        $expectedException = $e;
    }

    // Put your assertions outside of the `catch` block, otherwise
    // your test won't fail when the exception isn't thrown
    // (it will turn risky instead because there are no assertions)
    $this->assertInstanceOf(LimitReachedException::class, $expectedException);
    $this->assertSame('myExceptionProperty', $expectedException->getProperty());
}

0
投票

我把expectException放在发布的测试之前:

public function test_user_can_not_update_profile ()
{
    $user = User::factory()->create();

    $this->expectException(\PDOException::class);
    $this->expectException(\Illuminate\Database\QueryException::class);
    $profile = Profile::create([
        'website' => 'http://test.si'
    ]);

    $this->assertNull($user->fresh()->profile);
}
© www.soinside.com 2019 - 2024. All rights reserved.