m50/phpunit-expect

An expectation API for phpunit.

1.0.0 2021-07-11 07:07 UTC

This package is auto-updated.

Last update: 2024-10-08 11:42:17 UTC


README

psalm type coverage Test styleci status

Latest Stable Version Total Downloads License

An expectation API for PHPUnit, inspired by Jest for JS, and Pest for PHP.

Install

This requires PHP 8.

The best way to install this package is with Composer.

composer require --dev m50/phpunit-expect

Usage

For additional examples, check out the tests, every expectation is utilized in a test.

When writing tests, instead of using the standard assert, you can use expect.

<?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);
    }
}

Any assertion on your test case can be used with this API. For example:

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();
    }
}

It will replace toBe or to at the beginning of the function name with assert, so any assertion that has not been translated, or any custom assertion you may have, can be utilized with this.

Additionally, you can chain assertions:

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

And, it also supports proxied/higher-order expectations:

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;
}

Additionally, you can not any expectation as well:

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);
}

License

PHPUnit-Expect is open-sourced software licensed under the MIT license.