sassnowski/pest-plugin-contract-tests

一个用于在 Pest 中定义和实现合约测试的插件

v0.3.0 2024-03-26 08:48 UTC

README

此插件提供了一种在 Pest 中轻松定义和实现合约测试的方法。要了解更多关于合约测试是什么以及何时可能使用它们的信息,请查看我写的这篇博客文章

安装

使用 composer 安装插件

composer require sassnowski/pest-plugin-contract-tests

用法

要定义一个新的合约测试套件,您可以使用插件提供的 contractTest 函数。

// tests/Contracts/FilesystemContract.php

<?php

use function Sassnowski\PestContractTests\contractTest;

contractTest(Filesystem::class, function (Closure $getInstance) {
    it('can save a file for the first time', function () use ($getInstance) {
        /** @var Filesystem $fs */
        $fs = $getInstance();
        
        expect($fs->fileExists('::filename::'))->toBeFalse();
        
        $fs->storeFile(
            new MockFile('::contents::'),
            '::filename::',
        );
        
        expect($fs->fileExists('::filename::'))->toBeTrue();
    });
    
    it('throws an exception if a file with the same name already exists', function () use ($getInstance) {
        /** @var Filesystem $fs */
        $fs = $getInstance();

        $fs->storeFile(
            new MockFile('::contents::'),
            '::filename::'
        );

        // Trying to store another file with the same name should blow up.
        $fs->storeFile(
            new MockFile('::contents::'),
            '::filename::'
        ); 
    })->throws(
        FileAlreadyExistsException::class,
        "The file '::filename::' already exists"
    );
});

contractTest 方法接受两个参数

  1. 合约测试的名称。虽然这可以是任何字符串,但建议使用由合约测试描述的接口的完全限定类名 (FQCN)。
  2. 一个闭包,用于定义合约的实际测试用例。闭包内部的一切都像 vanilla Pest 一样工作。因此,您可以使用所有熟悉的功能,如高阶测试或 throws 方法来检查异常。

调用 contractTests 实际上并没有注册任何测试。它只是使合约测试可用于在其他测试文件中使用。要为特定类实际注册测试,您可以使用 implementsContract 函数。

// tests/InMemoryFilesystemTest.php

<?php

use function Sassnowski\PestContractTests\implementsContract;

implementsContract(Filesystem::class, fn () => new InMemoryFilesystem());

implementsContract 函数接受合约测试的名称,以及一个需要返回您想要测试的类实例的工厂函数。此工厂函数是传递给 contractTest 函数第二个参数的 $getInstance 参数。

这将现在为 InMemoryFilesystem 类注册所有在合约名称内部注册的测试用例。

$ vendor/bin/pest

PASS Tests\InMemoryFilesystemTest

✓ it can save a file for the first time                   0.12s
✓ it throws an exception if a file with the same name al… 0.08s

致谢

许可证

MIT