lelinea/api-snapshot-testing

提供用于api快照测试的PHPUnit断言

v1.5.0 2023-02-02 14:09 UTC

This package is auto-updated.

Last update: 2024-08-30 01:17:49 UTC


README

Build Status

提供用于快照测试的PHPUnit断言

安装

composer require --dev lelinea/snapshot-testing

基本用法

use Lelinea\ApiSnapshotTesting\MatchesSnapshots;

final class MyUnitTest extends TestCase
{
    use MatchesSnapshots;
    
    public function testJson()
    {
        $myJsonData = json_encode([
            'foo' => 'bar',
        ]);
        
        $this->assertMatchesJsonSnapshot($myJsonData, 'localhost/json-test-route');
    }    
    
    public function testXml()
    {
        $myXmlData = "<?xml version="1.0" encoding="UTF-8"?><root><id>7d644cc6-70fa-11e9-89e1-220d3e3a2561</id></root>";
        
        $this->assertMatchesXmlSnapshot($myXmlData, 'localhost/xml-test-route');
    } 
    
    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, [], false, ',', "'");
}

使用通配符

如果你的数据内容中有故意变化的内容,可以使用通配符

use Lelinea\ApiSnapshotTesting\MatchesSnapshots;
use Lelinea\ApiSnapshotTesting\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, 'localhost/json-test-route', [
            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, 'localhost/xml-test-route', [
            new UuidWildcard('id'),
        ]);
    }
}

这忽略了字段 "id" 给定的具体 uuid,只检查是否提供了有效的 uuid。

该库目前支持以下通配符

  • BooleanWildcard
  • IntegerWildcard
  • UuidWildcard
  • UuidOrNullWildcard
  • DateTimeWildcard
  • DateTimeOrNullWildcard
  • StringWildcard
  • StringOrNullWildcard

在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.