kigaroo / snapshot-testing
提供用于快照测试的PHPUnit断言
0.9.3
2024-04-25 09:34 UTC
Requires
- php: >=7.1
- ext-dom: *
- ext-json: *
- ext-mbstring: *
- ext-simplexml: *
- symfony/filesystem: ~2.8|~3.0|~4.0|~5.0
- symfony/property-access: ~2.8|~3.0|~4.0|~5.0
- webmozart/assert: ~1.2
Requires (Dev)
- doctrine/coding-standard: ~6.0|~8.0
- phpunit/phpunit: ^9.6
This package is auto-updated.
Last update: 2024-09-25 10:31:12 UTC
README
提供用于快照测试的PHPUnit断言
安装
composer require --dev kigaroo/snapshot-testing
基本用法
use KigaRoo\SnapshotTesting\MatchesSnapshots; final class MyUnitTest extends TestCase { use MatchesSnapshots; public function testJson() { $myJsonData = json_encode([ 'foo' => 'bar', ]); $this->assertMatchesJsonSnapshot($myJsonData); } public function testXml() { $myXmlData = "<?xml version="1.0" encoding="UTF-8"?><root><id>7d644cc6-70fa-11e9-89e1-220d3e3a2561</id></root>"; $this->assertMatchesXmlSnapshot($myJsonData); } public function testCsv() { $myCsvData = <<<CSV "foo bar";123 "foo bar";456 "foo bar";789 CSV; $this->assertMatchesCsvSnapshot($myCsvData); } public function testCsvVariant() { $myCsvData = <<<CSV 'foo bar',123 'foo bar',456 'foo bar',789 CSV; $this->assertMatchesCsvSnapshot($myCsvData, [], ',', "'"); } }
使用通配符
如果你的数据中有故意更改的内容,你可以使用通配符
use KigaRoo\SnapshotTesting\MatchesSnapshots; use KigaRoo\SnapshotTesting\Wildcard\UuidWildcard; final class MyUnitTest extends TestCase { use MatchesSnapshots; public function testJson() { $myJsonData = json_encode([ 'id' => '7d644cc6-70fa-11e9-89e1-220d3e3a2561', 'foo' => 'bar', ]); $this->assertMatchesJsonSnapshot($myJsonData, [ new UuidWildcard('id'), ]); } public function testXml() { $myXmlData = '<?xml version="1.0" encoding="UTF-8"?><root><id>7d644cc6-70fa-11e9-89e1-220d3e3a2561</id></root>'; $this->assertMatchesXmlSnapshot($myXmlData, [ new UuidWildcard('id'), ]); } public function testCsv() { $myCsvData = <<<CSV "7d644cc6-70fa-11e9-89e1-220d3e3a2561";123 "7d644cc6-70fa-11e9-89e1-220d3e3a2561";456 "7d644cc6-70fa-11e9-89e1-220d3e3a2561";789 CSV; $this->assertMatchesCsvSnapshot($myCsvData, [ new UuidWildcard('[*][0]'), ]); } }
这会忽略为“id”字段提供的具体uuid,只检查是否提供了有效的uuid。
该库目前支持以下通配符
- BooleanWildcard
- IntegerWildcard
- UuidWildcard
- UuidOrNullWildcard
- DateTimeWildcard
- DateTimeOrNullWildcard
- StringWildcard
- ObjectOrNullWildcard
在CI中的使用
当你在持续集成中运行测试时,你可能希望禁用快照的创建。
通过使用--without-creating-snapshots参数,如果快照不存在,PHPUnit将失败。
> ./vendor/bin/phpunit -d --without-creating-snapshots
1) ExampleTest::test_it_matches_a_string
Snapshot "ExampleTest__test_it_matches_a_string__1.txt" does not exist.
You can automatically create it by removing `-d --without-creating-snapshots` of PHPUnit's CLI arguments.