PHP code example of phrozenbyte / phpunit-array-asserts

1. Go to this page and download the library: Download phrozenbyte/phpunit-array-asserts library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

phrozenbyte / phpunit-array-asserts example snippets


// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait
ArrayAssertsTrait::assertAssociativeArray(
    array $constraints,            // an array with the expected keys and constraints to apply
    array|ArrayAccess $array,      // the associative array to check
    bool $allowMissing = false,    // whether missing items fail the constraint
    bool $allowAdditional = true,  // whether additional items fail the constraint
    string $message = ''           // additional information about the test
);

// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\AssociativeArray`
new AssociativeArray(
    array $constraints,
    bool $allowMissing = false,
    bool $allowAdditional = true
);

$data = [
    'id'      => 42,
    'name'    => 'Arthur Dent',
    'options' => [ 'has_towel' => true, 'panic' => false ],
];

// asserts that `$data` is an associative array with exactly the keys:
//     - "id" with a numeric value,
//     - "name" with the value "Arthur Dent", and
//     - "options" with another associative array with the key "panic", whose value must be a boolean
$this->assertAssociativeArray([
    'id'      => $this->isType(IsType::TYPE_INT),
    'name'    => 'Arthur Dent',
    'options' => $this->associativeArray([ 'panic' => $this->isType(IsType::TYPE_BOOL) ], true)
], $data);

$data = [
    'answer' => 21 /* half the truth */
];

$this->assertAssociativeArray([
    'answer' => 42
], $data);

// Will fail with the following message:
//
//     Failed asserting that associative array matches constraints.
//     +----------+-------+----------------------+
//     | Key      | Value | Constraint           |
//     +----------+-------+----------------------+
//     | 'answer' | 21    | Value is equal to 42 |
//     +----------+-------+----------------------+
//     [ ] Allow missing; [x] Allow additional

// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait
ArrayAssertsTrait::assertArrayHasKeyWith(
    string|int $key,              // the key of the item to check
    Constraint|mixed $constraint, // the constraint the item's value is applied to
    array|ArrayAccess $array,     // the array to check
    string $message = ''          // additional information about the test
);

// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\ArrayHasKeyWith`
new ArrayHasKeyWith(
    string|int $key,
    Constraint|mixed $constraint
);

$data = [
    'id'      => 42,
    'name'    => 'Arthur Dent',
    'options' => [ 'has_towel' => true, 'panic' => false ],
];

// asserts that $data has the item `name` with the value "Arthur Dent"
$this->assertArrayHasKeyWith('name', 'Arthur Dent', $data);

$data = [];

$this->assertArrayHasKeyWith('answer', 42, $data);

// Will fail with the following message:
//
//     Failed asserting that Array &0 () is an array that
//     has the key 'answer' whose value is equal to 42.

// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait
ArrayAssertsTrait::assertSequentialArray(
    array|Traversable $array,            // the sequential array to check
    int $minItems,                       //   // whether to ignore non-sequential keys
    string $message = ''                 // additional information about the test
);

// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\SequentialArray`
new SequentialArray(
    int $minItems = 0,
    int $maxItems = null,
    Constraint|mixed $constraint = null,
    bool $ignoreKeys = false
);

$data = [
    "The Hitchhiker's Guide to the Galaxy",
    "The Restaurant at the End of the Universe",
    "Life, the Universe and Everything",
    "So Long, and Thanks for All the Fish",
    "Mostly Harmless",
    "And Another Thing...",
];

// asserts that `$data` is a non-empty sequential array with non-empty items
$this->assertSequentialArray($data, 1, null, $this->logicalNot($this->isEmpty()));

$data = [];

$this->assertSequentialArray($data, 4, null, $this->is(IsType::TYPE_STRING));

// Will fail with the following message:
//
//     Failed asserting that Array &0 () is is a sequential array
//     with ≥ 4 items matching the constraint "is of type "string"".

// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait
ArrayAssertsTrait::assertArrayHasItemWith(
    int $index,                   // the index of the item to check
    Constraint|mixed $constraint, // the constraint the item's value is applied to
    array|Traversable $array,     // the array to check
    string $message = ''          // additional information about the test
);

// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\ArrayHasItemWith`
new ArrayHasItemWith(
    int $index,
    Constraint|mixed $constraint
);

$data = [
    '1979-10-12' => "The Hitchhiker's Guide to the Galaxy",
    '1980-10-00' => "The Restaurant at the End of the Universe",
    '1982-08-00' => "Life, the Universe and Everything",
    '1984-11-09' => "So Long, and Thanks for All the Fish",
    '1992-00-00' => "Mostly Harmless",
    '2009-10-12' => "And Another Thing...",
];

// asserts that `$data` contains "Life, the Universe and Everything" as third item (i.e. at index 2)
$this->assertArrayHasItemWith(2, "Life, the Universe and Everything");

$data = [];

$this->assertArrayHasItemWith(2, 'Arthur Dent', $data);

// Will fail with the following message:
//
//     Failed asserting that Array &0 () is an array that
//     has a value at index 2 which is equal to 'Arthur Dent'.


declare(strict_types=1);

namespace YourName\YourProject\Tests;

use PHPUnit\Framework\Constraint\IsType;
use PHPUnit\Framework\TestCase;
use PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait;

class MyTest extends TestCase
{
    use ArrayAssertsTrait;

    public function testWithPHPUnitArrayAsserts(): void
    {
        // 7 lines of easy to understand code to check the API response *with* PHPUnitArrayAsserts

        // implement your test, the result is stored in $responseData

        $responseData = [
            'users' => [
                [
                    'id'      => 42,
                    'name'    => 'Arthur Dent',
                    'options' => [ 'has_towel' => true, 'panic' => false ],
                ],
            ]
        ];

        $this->assertArrayHasKeyWith('users', $this->sequentialArray(1), $responseData);

        $this->assertAssociativeArray([
            'id'      => $this->isType(IsType::TYPE_INT),
            'name'    => 'Arthur Dent',
            'options' => $this->associativeArray([ 'panic' => $this->isType(IsType::TYPE_BOOL) ])
        ], $responseData['users'][0]);
    }
    
    public function testWithoutPHPUnitArrayAsserts(): void
    {
        // 17 lines of pretty repetitive code to check the API response *without* PHPUnitArrayAsserts

        // implement your test, the result is stored in $responseData

        $responseData = [
            'users' => [
                [
                    'id'      => 42,
                    'name'    => 'Arthur Dent',
                    'options' => [ 'has_towel' => true, 'panic' => false ],
                ],
            ]
        ];

        $this->assertArrayHasKey('users', $responseData);
        $this->assertIsArray($responseData['users']);
        $this->assertGreaterThanOrEqual(1, count($responseData['users'])); // won't work for Traversable

        $userData = $responseData['users'][0]; // we can't really rely on the existence of key "0" here :/

        $this->assertArrayHasKey('id', $userData);
        $this->assertIsInt($userData['id']);

        $this->assertArrayHasKey('name', $userData);
        $this->assertSame('Arthur Dent', $userData['name']);

        $this->assertArrayHasKey('options', $userData);
        $this->assertIsArray($userData['options']);

        $this->assertArrayHasKey('panic', $userData['options']);
        $this->assertIsBool($userData['options']['panic']);
    }
}