m50/phpunit-expect

PHPUnit 的期望 API。

1.0.0 2021-07-11 07:07 UTC

This package is auto-updated.

Last update: 2024-09-08 11:29:12 UTC


README

psalm type coverage Test styleci status

Latest Stable Version Total Downloads License

一个受 JavaScript 的 Jest 和 PHP 的 Pest 启发的 PHPUnit 期望 API。

安装

这需要 PHP 8。

使用 Composer 安装此包是最佳方式。

composer require --dev m50/phpunit-expect

使用方法

更多示例,请查看测试,每个期望都在测试中使用。

编写测试时,您可以使用 expect 代替标准的 assert。

<?php

namespace Tests;

use Expect\Traits\Expect;
use PHPUnit\Framework\TestCase;

class Test extends TestCase
{
    use Expect;

    public function testAdd()
    {
        $this->expect(2 + 2)->toBe(4);
    }
}

您可以使用此 API 对测试用例中的任何断言进行操作。例如

class CustomerAssertTest extends TestCase
{
    use Expect;

    public function assertCustomer($customer, string $message = ''): void
    {
        // Do some assertion
    }

    public function testCustomer()
    {
        // Populate the $customer variable with a possible Customer
        $this->expect($customer)->toBeCustomer();
    }
}

它将函数名称开头的 toBeto 替换为 assert,因此任何未翻译的断言或您可能拥有的任何自定义断言都可以使用此 API。

此外,您还可以链接断言

public function testStringChain()
{
    $this->expect('Hello World')
        ->toLowerCase() // Converts a string all to lower case, to do case insensitive assertions.
        ->toStartWith('hello')
        ->toEndWith('world')
    ;
}

并且,它还支持代理/高阶期望

public function testProxiedCalls()
{
    $this->expect(['first' => 1, 'second' => 2])
        ->first->toBe(1)
        ->second->toBe(2)
    ;

    $class = new \stdClass();
    $class->first = 1;
    $class->second = 2;

    $this->expect($class)
        ->first->toBe(1)
        ->second->toBe(2)
    ;
}

public function testSequence()
{
    $this->expect(['first' => 1, 'second' => 2])->sequence(
        first: fn (Expectation $e) => $e->toBe(1),
        second: fn(Expectation $e) => $e->toBe(2),
    );

    $class = new \stdClass();
    $class->first = 1;
    $class->second = 2;
}

此外,您还可以使用 not 来否定任何期望

public function testAdd()
{
    $this->expect(2 + 2)->not->toEqual(4);

    // Or you can use the function, if you prefer.
    $this->expect(2 + 2)->not()->toEqual(4);
}

许可

PHPUnit-Expect 是开源软件,受 MIT 许可证许可。查看许可证