You need to enable JavaScript to run this app. PHPUnit中expectException捕获异常后测试仍不通过如何解决?
优惠活动
大模型
产品
解决方案
定价
更多

PHPUnit中expectException捕获异常后测试仍不通过如何解决?

错误根因

核心问题是异常预期声明的执行顺序错误:
PHPUnit的expectException()方法必须在触发异常的代码执行前调用,你当前的代码先执行$cart->getItem($index)触发异常,程序直接中断抛出错误,后续的$this->expectException(\Exception::class);根本没有机会执行,PHPUnit接收不到异常预期的声明,就会判定为用例执行失败。

修复方案

调换测试用例中两行代码的顺序即可,修正后的测试代码如下:

public function itThrowsExceptionWhileGettingNonExistentItem(int $index): void
{
    $product = $this->buildTestProduct(1, 15000);

    $cart = new Cart();
    $cart->addProduct($product, 1);
    // 先声明预期异常
    $this->expectException(\Exception::class);
    // 再执行会抛出异常的业务代码
    $cart->getItem($index);
}

可选优化

你还可以补充异常的错误码、错误信息校验,避免业务抛出其他同类型异常时误判用例通过:

$this->expectException(\Exception::class);
$this->expectExceptionCode(404);
$this->expectExceptionMessage(sprintf('Item with index(%s) not exists', $index));

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 10:54:02