You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PHPUnit检查LimitReachedException的resumeAt属性值

PHPUnit验证自定义异常的属性值

你已经定义了带resumeAt属性的自定义异常LimitReachedException,当前仅通过$this->expectException(LimitReachedException::class)验证异常类型,要同时验证resumeAt属性值,有两种常用方法:

方法一:手动捕获异常并断言

通过try-catch捕获抛出的异常,同时验证异常类型和属性值:

// 引入异常类
use App\Exception\LimitReachedException;

public function testLimitReachedExceptionWithResumeAt()
{
    try {
        // 执行会触发该异常的业务代码
        $this->yourMethodThatThrowsException();
        // 如果没抛出异常,标记测试失败
        $this->fail('未抛出预期的LimitReachedException');
    } catch (LimitReachedException $exception) {
        // 验证resumeAt属性值
        $expectedResumeTime = new \DateTime('2024-05-20 14:30:00');
        $this->assertEquals($expectedResumeTime, $exception->getResumeAt());
    }
}

方法二:利用PHPUnit的getThrowable()方法

先设置预期异常类型,执行代码后获取异常实例进行断言:

use App\Exception\LimitReachedException;

public function testLimitReachedExceptionResumeAtValue()
{
    $this->expectException(LimitReachedException::class);
    
    try {
        $this->yourMethodThatThrowsException();
    } catch (LimitReachedException $exception) {
        // 先验证属性值
        $expectedResumeTime = new \DateTime('2024-05-20 14:30:00');
        $this->assertEquals($expectedResumeTime, $exception->getResumeAt());
        
        // 重新抛出异常,让PHPUnit的expectException断言生效
        throw $exception;
    }
}

注意:确保你的LimitReachedException类已经实现了getResumeAt() getter方法,否则无法访问私有属性$resumeAt。

内容的提问来源于stack exchange,提问作者Oli

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 05:35:10