|
1 | 1 | PHPUnitArrayAssertions |
2 | 2 | ====================== |
3 | 3 |
|
4 | | -`PHPUnitArrayAssertions` is a small [PHPUnit](https://phpunit.de/) extension to improve testing of PHP arrays and array-like data. It allows developers to test structure and data in single assertion, making test cases less repetitive and easier to understand. |
| 4 | +`PHPUnitArrayAssertions` is a small [PHPUnit](https://phpunit.de/) extension to improve testing of PHP arrays and array-like data. It introduces the `AssociativeArray`, `ArrayHasKeyWith`, `SequentialArray`, and `ArrayHasItemWith` constraints. It is often used for API testing to assert whether an API result matches certain criteria - regarding both its structure, and the data. |
| 5 | + |
| 6 | +This PHPUnit extension allows developers to test structure and data in single assertion, making test cases less repetitive and easier to understand. In some way it's an alternative to PHPUnit's `ArraySubset` constraint that was deprecated in PHPUnit 8 and removed in PHPUnit 9 - just way more powerful and less confusing. Refer to the ["Usage" section](#usage) and ["Example" section](#example) below for more info. |
| 7 | + |
| 8 | +Made with :heart: by [Daniel Rudolf](https://www.daniel-rudolf.de). `PHPUnitArrayAssertions` is free and open source software, released under the terms of the [MIT license](https://github.com/PhrozenByte/phpunit-array-asserts/blob/master/LICENSE). |
| 9 | + |
| 10 | +Install |
| 11 | +------- |
| 12 | + |
| 13 | +`PHPUnitArrayAssertions` is available on [Packagist.org](https://packagist.org/packages/phrozenbyte/phpunit-array-asserts) and can be installed using [Composer](https://getcomposer.org/): |
| 14 | + |
| 15 | +```shell |
| 16 | +composer require --dev phrozenbyte/phpunit-array-asserts |
| 17 | +``` |
| 18 | + |
| 19 | +This PHPUnit extension was initially written for PHPUnit 8, but should work fine with any later PHPUnit version. If it doesn't, please don't hesitate to open a [new Issue on GitHub](https://github.com/PhrozenByte/phpunit-array-asserts/issues/new), or, even better, create a Pull Request with a proposed fix. |
| 20 | + |
| 21 | +Usage |
| 22 | +----- |
| 23 | + |
| 24 | +There are three (basically equivalent) options to use `PHPUnitArrayAssertions`: |
| 25 | + |
| 26 | +- By using the static class `PhrozenByte\PHPUnitArrayAsserts\Assert` |
| 27 | +- By using the trait `PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` in your test case |
| 28 | +- By creating new constraint instances (`PhrozenByte\PHPUnitArrayAsserts\Constraint\…`) |
| 29 | + |
| 30 | +All options do the same, the only difference is that the static class and trait both throw `PHPUnit\Framework\InvalidArgumentException` exceptions for invalid parameters. Creating new constraint instances is useful for advanced assertions, e.g. together with `PHPUnit\Framework\Constraint\LogicalAnd`. |
| 31 | + |
| 32 | +### Constraint `AssociativeArray` |
| 33 | + |
| 34 | +The `AssociativeArray` constraint asserts that a value is an associative array matching a given structure and that the array's items pass other constraints. |
| 35 | + |
| 36 | +Any native array and `ArrayAccess` object is considered an associative array, no matter which keys they use. However, the array's items are applied to the matching constraint (parameter `$consotraints`). By default, additional items will fail the constraint (parameter `$allowAdditional`, defaults to `false`). The same is true when items are missing (parameter `$allowMissing`, defaults to `false`). The expected keys and constraints to apply, as well as whether additional and/or missing items should fail the constraint, are passed in the constructor. |
| 37 | + |
| 38 | +**Usage:** |
| 39 | + |
| 40 | +```php |
| 41 | +// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait |
| 42 | +self::assertAssociativeArray( |
| 43 | + array $constraints, // an associative array with the expected keys and constraints to apply |
| 44 | + array|ArrayAccess $array, // the associative array to check |
| 45 | + bool $allowAdditional = false, // whether additional items should fail the constraint |
| 46 | + bool $allowMissing = false, // whether missing items should fail the constraint |
| 47 | + string $message = '' // additional information about the test |
| 48 | +); |
| 49 | + |
| 50 | +// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\AssociativeArray` |
| 51 | +new AssociativeArray( |
| 52 | + array $constraints, |
| 53 | + bool $allowAdditional = false, |
| 54 | + bool $allowMissing = false |
| 55 | +); |
| 56 | +``` |
| 57 | + |
| 58 | +**Example:** |
| 59 | + |
| 60 | +```php |
| 61 | +$data = [ |
| 62 | + 'id' => 42, |
| 63 | + 'name' => 'Arthur Dent', |
| 64 | + 'options' => [ 'has_towel' => true, 'panic' => false ], |
| 65 | +]; |
| 66 | + |
| 67 | +// asserts that `$data` is an associative array with exactly the keys: |
| 68 | +// - "id" with a numeric value, |
| 69 | +// - "name" with the value "Arthur Dent", and |
| 70 | +// - "options" with another associative array with the key "panic", whose value must be a boolean |
| 71 | +self::assertAssociativeArray([ |
| 72 | + 'id' => new IsType(IsType::TYPE_INT), |
| 73 | + 'name' => new IsIdentical('Arthur Dent'), |
| 74 | + 'options' => new AssociativeArray([ 'panic' => new IsType(IsType::TYPE_BOOL) ], true) |
| 75 | +], $data); |
| 76 | +``` |
| 77 | + |
| 78 | +### Constraint `ArrayHasKeyWith` |
| 79 | + |
| 80 | +The `ArrayHasKeyWith` constraint asserts that an array has a given key and that its value passes another constraint. |
| 81 | + |
| 82 | +Accepts both native arrays and `ArrayAccess` objects. The constraint (parameter `$constraint`) will fail if the key (parameter `$key`) doesn't exist in the array. The item's key and the constraint the value must pass are passed in the constructor. |
| 83 | + |
| 84 | +**Usage:** |
| 85 | + |
| 86 | +```php |
| 87 | +// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait |
| 88 | +self::assertArrayHasKeyWith( |
| 89 | + string|int $key, // the key of the item to check |
| 90 | + Constraint $constraint, // the constraint the item's value is applied to |
| 91 | + array|ArrayAccess $array, // the array to check |
| 92 | + string $message = '' // additional information about the test |
| 93 | +); |
| 94 | + |
| 95 | +// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\ArrayHasKeyWith` |
| 96 | +new ArrayHasKeyWith( |
| 97 | + string|int $key, |
| 98 | + Constraint $constraint |
| 99 | +); |
| 100 | +``` |
| 101 | + |
| 102 | +**Example:** |
| 103 | + |
| 104 | +```php |
| 105 | +$data = [ |
| 106 | + 'id' => 42, |
| 107 | + 'name' => 'Arthur Dent', |
| 108 | + 'options' => [ 'has_towel' => true, 'panic' => false ], |
| 109 | +]; |
| 110 | + |
| 111 | +// asserts that $data has the item `name` with the value "Arthur Dent" |
| 112 | +self::ArrayHasKeyWith('name', new IsIdentical('Arthur Dent'), $data); |
| 113 | +``` |
| 114 | + |
| 115 | +### Constraint `SequentialArray` |
| 116 | + |
| 117 | +The `SequentialArray` constraint asserts that a value is like a sequential array, has a minimum and/or maximum number of items, and that all items pass another constraint. |
| 118 | + |
| 119 | +Sequential arrays are defined as ordered lists with incrementing numeric keys starting from zero. This is especially true for native sequential arrays like `[ "foo", "bar" ]`. Empty arrays are considered valid, too. `Traversable` objects must have sequential keys to be considered valid. The expected minimum (parameter `$minItems`, defaults to `0`) and/or maximum (parameter `$maxItems`, defaults to `null`, meaning infinite) number of items, and the constraint to apply all items to (optional parameter `$constraint`), are passed in the constructor. |
| 120 | + |
| 121 | +This constraint will fully traverse any `Traversable` object given. This also means that any `Generator` will be fully exhausted. If possible, it will try to restore an `Iterator`'s pointer to its previous state. |
| 122 | + |
| 123 | +**Usage:** |
| 124 | + |
| 125 | +```php |
| 126 | +// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait |
| 127 | +self::assertSequentialArray( |
| 128 | + array|Traversable $array, // the sequential array to check |
| 129 | + int $minItems, // required minimum number of items |
| 130 | + int $maxItems = null, // required maximum number of items (pass null for infinite) |
| 131 | + Constraint $constraint = null, // optional constraint to apply all items to |
| 132 | + string $message = '' // additional information about the test |
| 133 | +); |
| 134 | + |
| 135 | +// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\SequentialArray` |
| 136 | +new SequentialArray( |
| 137 | + int $minItems = 0, |
| 138 | + int $maxItems = null, |
| 139 | + Constraint $constraint = null |
| 140 | +); |
| 141 | +``` |
| 142 | + |
| 143 | +**Example:** |
| 144 | + |
| 145 | +```php |
| 146 | +$data = [ |
| 147 | + "The Hitchhiker's Guide to the Galaxy", |
| 148 | + "The Restaurant at the End of the Universe", |
| 149 | + "Life, the Universe and Everything", |
| 150 | + "So Long, and Thanks for All the Fish", |
| 151 | + "Mostly Harmless", |
| 152 | + "And Another Thing...", |
| 153 | +]; |
| 154 | + |
| 155 | +// asserts that `$data` is a non-empty sequential array with non-empty items |
| 156 | +self::assertSequentialArray($data, 1, null, self::logicalNot(new IsEmpty())); |
| 157 | +``` |
| 158 | + |
| 159 | +### Constraint `ArrayHasItemWith` |
| 160 | + |
| 161 | +The `ArrayHasItemWith` constraint asserts that an array has a item at a given index and that its value passes another constraint. |
| 162 | + |
| 163 | +Accepts both native arrays and `Traversable` objects. The constraint will fail if the array has less items than required. The index of the item to check (parameter `$index`), and the constraint its value must pass (parameter `$constraint`) are passed in the constructor. |
| 164 | + |
| 165 | +This constraint will fully traverse any `Traversable` object given. This also means that any `Generator` will be fully exhausted. It doesn't restore an `Iterator`'s pointer to its previous state. |
| 166 | + |
| 167 | +**Usage:** |
| 168 | + |
| 169 | +```php |
| 170 | +// using `\PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait` trait |
| 171 | +self::assertArrayHasItemWith( |
| 172 | + int $index, // the index of the item to check |
| 173 | + Constraint $constraint, // the constraint the item's value is applied to |
| 174 | + array|Traversable $array, // the array to check |
| 175 | + string $message = '' // additional information about the test |
| 176 | +); |
| 177 | + |
| 178 | +// using new instance of `\PhrozenByte\PHPUnitArrayAsserts\Constraint\ArrayHasItemWith` |
| 179 | +new ArrayHasItemWith( |
| 180 | + int $index, |
| 181 | + Constraint $constraint |
| 182 | +); |
| 183 | +``` |
| 184 | + |
| 185 | +**Example:** |
| 186 | + |
| 187 | +```php |
| 188 | +$data = [ |
| 189 | + '1979-10-12' => "The Hitchhiker's Guide to the Galaxy", |
| 190 | + '1980-10-00' => "The Restaurant at the End of the Universe", |
| 191 | + '1982-08-00' => "Life, the Universe and Everything", |
| 192 | + '1984-11-09' => "So Long, and Thanks for All the Fish", |
| 193 | + '1992-00-00' => "Mostly Harmless", |
| 194 | + '2009-10-12' => "And Another Thing...", |
| 195 | +]; |
| 196 | + |
| 197 | +// asserts that `$data` contains "Life, the Universe and Everything" as third item (i.e. at index 2) |
| 198 | +self::ArrayHasItemWith(2, new IsIdentical("Life, the Universe and Everything"")); |
| 199 | +``` |
| 200 | + |
| 201 | +Example |
| 202 | +------- |
| 203 | + |
| 204 | +```php |
| 205 | +<?php |
| 206 | +declare(strict_types=1); |
| 207 | + |
| 208 | +namespace YourName\YourProject\Tests; |
| 209 | + |
| 210 | +use PHPUnit\Framework\Constraint\IsIdentical; |
| 211 | +use PHPUnit\Framework\Constraint\IsType; |
| 212 | +use PHPUnit\Framework\TestCase; |
| 213 | +use PhrozenByte\PHPUnitArrayAsserts\ArrayAssertsTrait; |
| 214 | +use PhrozenByte\PHPUnitArrayAsserts\Constraint\AssociativeArray; |
| 215 | +use PhrozenByte\PHPUnitArrayAsserts\Constraint\SequentialArray; |
| 216 | + |
| 217 | +class MyTest extends TestCase |
| 218 | +{ |
| 219 | + use ArrayAssertsTrait; |
| 220 | + |
| 221 | + public function testWithPHPUnitArrayAsserts(): void |
| 222 | + { |
| 223 | + // implement your test, the result is stored in $responseData |
| 224 | + |
| 225 | + $responseData = [ |
| 226 | + 'users' => [ |
| 227 | + [ |
| 228 | + 'id' => 42, |
| 229 | + 'name' => 'Arthur Dent', |
| 230 | + 'options' => [ 'has_towel' => true, 'panic' => false ], |
| 231 | + ], |
| 232 | + ] |
| 233 | + ]; |
| 234 | + |
| 235 | + $this->assertArrayHasKeyWith('users', new SequentialArray(1), $responseData); |
| 236 | + |
| 237 | + $this->assertAssociativeArray([ |
| 238 | + 'id' => new IsType(IsType::TYPE_INT), |
| 239 | + 'name' => new IsIdentical('Arthur Dent'), |
| 240 | + 'options' => new AssociativeArray([ 'panic' => new IsType(IsType::TYPE_BOOL) ], true) |
| 241 | + ], $responseData['users'][0]); |
| 242 | + |
| 243 | + // 7 lines of easier to understand code to check the API response *with* PHPUnitArrayAsserts |
| 244 | + } |
| 245 | + |
| 246 | + public function testWithoutPHPUnitArrayAsserts(): void |
| 247 | + { |
| 248 | + // implement your test, the result is stored in $responseData |
| 249 | + |
| 250 | + $responseData = [ |
| 251 | + 'users' => [ |
| 252 | + [ |
| 253 | + 'id' => 42, |
| 254 | + 'name' => 'Arthur Dent', |
| 255 | + 'options' => [ 'has_towel' => true, 'panic' => false ], |
| 256 | + ], |
| 257 | + ] |
| 258 | + ]; |
| 259 | + |
| 260 | + $this->assertArrayHasKey('users', $responseData); |
| 261 | + $this->assertIsArray($responseData['users']); |
| 262 | + $this->assertGreaterThanOrEqual(1, count($responseData['users'])); // won't work for Traversable |
| 263 | + |
| 264 | + $userData = $responseData['users'][0]; // we can't really rely on the existence of key "0" here :/ |
| 265 | + $this->assertEmpty(array_diff_key($userData, [ 'id' => true, 'name' => true, 'options' => true ])); |
| 266 | + |
| 267 | + $this->assertArrayHasKey('id', $userData); |
| 268 | + $this->assertIsInt($userData['id']); |
| 269 | + |
| 270 | + $this->assertArrayHasKey('name', $userData); |
| 271 | + $this->assertSame('Arthur Dent', $userData['name']); |
| 272 | + |
| 273 | + $this->assertArrayHasKey('options', $userData); |
| 274 | + $this->assertIsArray($userData['options']); |
| 275 | + |
| 276 | + $this->assertArrayHasKey('panic', $userData['options']); |
| 277 | + $this->assertIsBool($userData['options']['bool']); |
| 278 | + |
| 279 | + // 18 lines of pretty repetitive code to check the API response *without* PHPUnitArrayAsserts |
| 280 | + } |
| 281 | +} |
| 282 | +``` |
0 commit comments