32人参与 • 2025-03-30 • Ruby
我在2015年中开始学习纯php。然后,我熟悉了codeigniter 3和laravel 5.1。多年来,laravel 是我选择的框架,而且我仍然坚持使用它。与其他流行的 php 项目一样,我认为 phpunit 是单元测试的唯一选择。但2021年佩斯来了,情况发生了一点变化。它是由 laravel 工程师 nuno maduro 创建的,他还制作了许多在 php 和 laravel 社区中广泛使用的优秀项目/包。
从 pest 的第一天起,我就不再关心它了,因为 phpunit 对我来说已经足够了,我懒得学习这个新的测试工具。但 laravel 社区发展得越多,推荐的 pest 就越多。 spatie、livewire、filament 等的许多 laravel 项目/包都使用 pest。所以问题是当测试与它们相关的东西时,我必须移植到 phpunit。我似乎别无选择。是时候去看看佩斯了。
在安装部分之后,我使用 pest 创建我的第一个 php 项目。
mkdir ~/herd/lerning-pest cd ~/herd/learning-pest composer require pestphp/pest --dev --with-all-dependencies ./vendor/bin/pest --init
目录结构与phpunit几乎相同。不同之处在于测试的外观。它是基于闭包而不是基于类的。
<?php // tests/unit/exampletest.php test('example', function () { expect(true)->tobetrue(); });
我知道使用 closure 可以在运行时将方法延迟附加到对象。所以这可以像这样在 phpunit 中重写。
<?php // tests/unit/exampletest.php class exampletest extends \phpunit\framework\testcase { public function test_example() { $this->asserttrue(true); } }
它说 pest 断言语法受到 ruby 的 rspec 和 jest 的启发,我不知道。所以,我对他们也没有太大兴趣。对我来说,断言语法如何并不重要。
我只是喜欢运行测试时显示的结果。我认为它比 phpunit 更漂亮、更干净。
这些是我在 phpunit 中使用最多的断言。
$this->assertsame($expected, $actual); $this->asserttrue($condition); $this->assertfalse($condition); $this->assertnull($actual); $this->assertempty($array); $this->assertcount($count, $countable); $this->assertinstanceof($type, $instance);
它们可以很容易地用 pest 重写。
expect($actual)->tobe($expected); expect($condition)->tobetrue(); expect($condition)->tobefalse(); expect($actual)->tobenull(); expect($actual)->tobeempty(); expect($actual)->tobeinstanceof($type);
正如我之前提到的,pest 断言语法很好,但我目前坚持使用 phpunit,因为我不需要研究新的 api。不管怎样,我更喜欢 phpunit 断言,并且只使用 pest 中独特的东西。架构测试就是一个例子。我的测试文件如下所示。
<?php test("all php files in learningpest namespace must have strict mode enabled", function () { arch() ->expect('learningpest') ->tousestricttypes(); }); test('all phpunit assertions are available for pest', function () { $instance = new \stdclass(); $getinstance = function () use ($instance) { return $instance; }; $this->assertsame($instance, $getinstance()); $this->assertinstanceof(stdclass::class, $instance); $this->asserttrue(1 < 2); $this->assertfalse(1 > 2); $value = null; $this->assertnull($value); $this->assertempty([]); $array = [1, 2, 3]; $this->assertcount(3, $array); });
有许多强制功能使我能够像 phpunit 一样在 pest 中工作。他们在这里:
mockery 是一个独立的库,所以我不在这里列出它。
另一方面,pest 有很多东西可能会派上用场,例如架构、快照或压力测试和插件。我会在编写测试时发现它们。
如果你是一个没有使用过 pest 的 php 开发者,不妨尝试一下。
以上就是我最终尝试了 pest for php & laravel,然后进行了切换的详细内容,更多请关注代码网其它相关文章!
您想发表意见!!点此发布评论
版权声明:本文内容由互联网用户贡献,该文观点仅代表作者本人。本站仅提供信息存储服务,不拥有所有权,不承担相关法律责任。 如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 2386932994@qq.com 举报,一经查实将立刻删除。
发表评论