如何用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
相关产品推荐
相关产品推荐

