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

使用PestPHP测试框架时toMatchArray数组断言失败问题求助

PestPHP toMatchArray断言失败问题排查与解决

你的问题出在数组键的类型不匹配:Validator返回的错误数组$e是数字索引(0、1),但你在断言里写的预期数组用了字符串类型的键('0'、'1'),Pest的toMatchArray会严格校验键的类型,导致断言失败。

解决方法

直接把预期数组的键改成数字类型即可:

include '../../test/validator.php';

$v = new Validator();
$a = ['password' => '1'];
$b = ['password' => ['good_password', 'minLen:8']];
$v->validate($a, $b);
$e = $v->error();

expect($e)->toMatchArray([
    0 => ['form_err' => "password: Password must contain 6 characters of letters, numbers and at least one special character."],
    1 => ['form_err' => "password: Password should be minimum minLen:8 characters"],
]);

可选优化:不依赖索引顺序的断言

如果错误信息的顺序可能变化,建议用toContainEqual逐个验证错误项,这样更灵活:

// 验证每个错误消息存在即可,不关心顺序
expect($e)->toContainEqual(['form_err' => "password: Password must contain 6 characters of letters, numbers and at least one special character."]);
expect($e)->toContainEqual(['form_err' => "password: Password should be minimum minLen:8 characters"]);

补充说明

Pest的toMatchArray断言会同时校验键的值和类型,数字索引(0)和字符串键名('0')在PHP里是两个不同的键,所以即使对应的值完全一致,断言也会失败。从你打印的$e结果能明确看到返回的是数字索引数组,调整预期数组的键类型就能解决问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 08:15:11