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

