
assertEquals、assertJsonStringEqualsJsonString 等断言,逐一检查输出的每一个属性、每一个标签、每一个字符。这种手动断言的方式有几个明显的弊端:
幸运的是,PHP 社区的 Composer 生态为我们提供了强大的解决方案。今天,我们要介绍的英雄是 spatie/pest-plugin-snapshots,一个专为 Pest 测试框架设计的快照测试插件。
Composer在线学习地址:学习地址
快照测试(Snapshot Testing)是一种非常直观且强大的测试范式。它的核心思想不是让你逐一断言输出的每一个细节,而是让你“拍一张快照”。
spatie/pest-plugin-snapshots 插件正是将这种能力带到了我们喜爱的 Pest 测试框架中,它底层依赖于 Spatie 优秀的 phpunit-snapshot-assertions 包,确保了功能强大和稳定。
spatie/pest-plugin-snapshots
使用 Composer 安装这个插件非常简单,因为它是一个开发依赖,所以我们使用 --dev 标志:
<code class="bash">composer require spatie/pest-plugin-snapshots --dev</code>
安装完成后,你就可以在 Pest 测试文件中使用它了。以下是一些实用的例子:
假设你有一个 Order 类,它有一个 toString() 方法返回订单的字符串表示,以及一个 toJson() 方法返回订单的 JSON 表示。
1. 快照字符串输出
<pre class="brush:php;toolbar:false;">// tests/Unit/OrderTest.php
use function Spatie\Snapshots\assertMatchesSnapshot;
it('can be cast to string', function () {
$order = new Order(1, 'Product A', 99.99); // 假设 Order 构造函数接收 ID, name, price
// 使用 assertMatchesSnapshot 检查字符串输出
assertMatchesSnapshot($order->toString());
});当你第一次运行这个测试时,spatie/pest-plugin-snapshots 会在你的 __snapshots__ 目录下创建一个快照文件(例如 OrderTest__it_can_be_cast_to_string__1.snap),其中包含 $order->toString() 的输出。
2. 快照 JSON 输出
<pre class="brush:php;toolbar:false;">// tests/Unit/OrderTest.php
use function Spatie\Snapshots\assertMatchesJsonSnapshot;
it('can be cast to json', function () {
$order = new Order(1, 'Product B', 120.00);
// 使用 assertMatchesJsonSnapshot 检查 JSON 输出
assertMatchesJsonSnapshot($order->toJson());
});同样,第一次运行会生成一个 JSON 快照文件。
3. 使用 Pest 的 expect() 语法
如果你更喜欢 Pest 风格的 expect() 语法,这个插件也完美支持:
<pre class="brush:php;toolbar:false;">// tests/Unit/OrderTest.php
it('can be cast to string with expect', function () {
$order = new Order(2, 'Product C', 50.50);
// 使用 expect()->toMatchSnapshot()
expect($order->toString())->toMatchSnapshot();
});
it('can be cast to json with expect', function () {
$order = new Order(2, 'Product D', 25.00);
// 使用 expect()->toMatchJsonSnapshot()
expect($order->toJson())->toMatchJsonSnapshot();
});更新快照
当你的代码逻辑发生变化,导致快照测试失败时,Pest 会提示你快照不匹配。如果这是预期内的改变,你可以通过在运行测试时添加 --update-snapshots 标志来更新快照:
<code class="bash">./vendor/bin/pest --update-snapshots</code>
Pest 会重新生成所有不匹配的快照文件,让你的测试再次通过。
spatie/pest-plugin-snapshots 的优势与实际应用效果引入 spatie/pest-plugin-snapshots 插件后,你将体验到以下显著优势:
--update-snapshots 命令,所有相关的快照都会自动更新,大大节省了维护时间。spatie/pest-plugin-snapshots 是一个强大的工具,它通过引入快照测试机制,彻底解决了 PHP 项目中复杂输出测试的痛点。它不仅能让你的测试代码更加简洁、易于维护,还能有效提升测试的覆盖率和稳定性。如果你正在使用 Pest 进行测试,并且经常面临复杂字符串、JSON 或 HTML 输出的测试挑战,那么强烈推荐你尝试这个插件,它将为你的开发工作带来质的飞跃。让快照测试成为你测试工具箱中的一把利器,助你构建更健壮、更易维护的 PHP 应用!
以上就是如何解决复杂输出的测试痛点,SpatiePestSnapshot插件助你高效测试的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号