PHPackages                             fallegahq/json-test-utils - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Testing &amp; Quality](/categories/testing)
4. /
5. fallegahq/json-test-utils

ActiveLibrary[Testing &amp; Quality](/categories/testing)

fallegahq/json-test-utils
=========================

JSON testing utilities for PHPUnit 11+

0.0.1alpha6(1y ago)111MITPHPPHP ^8.2CI passing

Since Apr 12Pushed 1y ago1 watchersCompare

[ Source](https://github.com/FallegaHQ/phpunit-json-test-utils)[ Packagist](https://packagist.org/packages/fallegahq/json-test-utils)[ RSS](/packages/fallegahq-json-test-utils/feed)WikiDiscussions master Synced 1mo ago

READMEChangelog (3)Dependencies (6)Versions (4)Used By (0)

JSON Test Utilities for PHPUnit
===============================

[](#json-test-utilities-for-phpunit)

---

[![Version](https://camo.githubusercontent.com/a3b6fee768315169798b5b8b0cb2d4c834733187e08a7a6468a1dddb7be44eaf/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f66616c6c65676168712f6a736f6e2d746573742d7574696c732e7376673f7374796c653d666f722d7468652d6261646765)](https://img.shields.io/packagist/v/fallegahq/json-test-utils.svg?style=for-the-badge)[![Downloads](https://camo.githubusercontent.com/c409187da9ddbb04856c771c8dd615977aa45f9522c4428d2518e354a9c3c48a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f66616c6c65676168712f6a736f6e2d746573742d7574696c732e7376673f7374796c653d666f722d7468652d6261646765)](https://packagist.org/packages/fallegahq/json-test-utils)[![Downloads](https://camo.githubusercontent.com/88fb4ef5a0524635b7fcc588fbdad77931638a087457e440e624e4b320288a1b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f616374696f6e732f776f726b666c6f772f7374617475732f66616c6c65676168712f706870756e69742d6a736f6e2d746573742d7574696c732f72656c656173652e796d6c3f7374796c653d666f722d7468652d6261646765)](https://github.com/fallegahq/phpunit-json-test-utils/actions/workflows/release.yml)

[![Contributors](https://camo.githubusercontent.com/ee4463da743fbac82044a3b2e6b14273c9d96b2a10e9dcdebd61e0e222ff1c13/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f636f6e7472696275746f72732f46616c6c65676148512f706870756e69742d6a736f6e2d746573742d7574696c732e7376673f7374796c653d666f722d7468652d6261646765)](https://github.com/FallegaHQ/phpunit-json-test-utils/graphs/contributors)[![Forks](https://camo.githubusercontent.com/c47908cae731d9d9dc4a60a2e6496c9e60306e443b2e58a78ab70b8251563d25/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f666f726b732f46616c6c65676148512f706870756e69742d6a736f6e2d746573742d7574696c732e7376673f7374796c653d666f722d7468652d6261646765)](https://github.com/FallegaHQ/phpunit-json-test-utils/network/members)[![Stargazers](https://camo.githubusercontent.com/eec507b29eac0922ca585fadda3e059759495ae592c6c0cd9eb7ef3c8ed8735b/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f73746172732f46616c6c65676148512f706870756e69742d6a736f6e2d746573742d7574696c732e7376673f7374796c653d666f722d7468652d6261646765)](https://github.com/FallegaHQ/phpunit-json-test-utils/stargazers)[![Issues](https://camo.githubusercontent.com/27496d3d487c6f6cb069f17e79aff97a60662b88c32ae7570f3553f6f6fd96b4/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6973737565732f46616c6c65676148512f706870756e69742d6a736f6e2d746573742d7574696c732e7376673f7374796c653d666f722d7468652d6261646765)](https://github.com/FallegaHQ/phpunit-json-test-utils/issues)[![MIT License](https://camo.githubusercontent.com/137dd2028bb2cb6c6f38b6f1a41a6ae468c753f1f6deb1a2c32c6a7c3456c460/68747470733a2f2f696d672e736869656c64732e696f2f6769746875622f6c6963656e73652f46616c6c65676148512f706870756e69742d6a736f6e2d746573742d7574696c732e7376673f7374796c653d666f722d7468652d6261646765266c6f676f3d4d4954)](https://github.com/FallegaHQ/phpunit-json-test-utils/blob/master/LICENSE)

---

The tool
--------

[](#the-tool)

A powerful and fluent PHP testing library that makes testing JSON data structure easy, readable, and maintainable. Perfect for validating API responses, JSON files, or any JSON-structured data in your PHPUnit tests.

Features
--------

[](#features)

- Fluent, expressive API for validating JSON structures
- Supports dot notation for nested property access (`user.address.zipcode`)
- Type checking for values (string, integer, array, etc.)
- Comprehensive validation rules (regex, email, URL, date, etc.)
- Supports custom validation callbacks
- Schema validation for complex structures
- Detailed error messages for failed assertions

([back to top](#top))

Installation
------------

[](#installation)

You can install the package via composer:

```
composer require --dev fallegahq/json-test-utils
```

([back to top](#top))

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

Code example```
use FallegaHQ\JsonTestUtils\JsonAssertions;

class ApiResponseTest extends \PHPUnit\Framework\TestCase
{
    use JsonAssertions;

    public function testApiResponse()
    {
        $response = $this->getApiResponse(); // Returns JSON string or array

        // Simple key existence check
        $this->assertJsonHasKey($response, 'data');

        // Check for a specific value
        $this->assertJsonEquals($response, 'status', 'success');

        // Check value type
        $this->assertJsonType($response, 'data.items', 'array');

        // Check using a custom condition
        $this->assertJsonCondition($response, 'data.count', function($value) {
            return $value > 0 && $value < 100;
        });
    }
}
```

### Fluent API

[](#fluent-api)

Code example```
public function testJsonStructure()
{
    $json = '{"user": {"name": "John", "email": "john@example.com", "age": 30}}';

    $this->assertValidJson($json)
        ->hasKey('user')
        ->isType('user', 'array')
        ->hasKey('user.name')
        ->equals('user.name', 'John')
        ->isEmail('user.email')
        ->isType('user.age', 'integer')
        ->assert();
}
```

### Schema Validation

[](#schema-validation)

Code example```
public function testComplexJsonSchema()
{
    $json = '{"users": [{"id": 1, "name": "John"}, {"id": 2, "name": "Jane"}]}';

    $this->assertValidJson($json)
        ->matchesSchema([
            'users' => [
                'type' => 'array',
                'required' => true
            ]
        ])
        ->isType('users.0.id', 'integer')
        ->isType('users.0.name', 'string')
        ->hasLength('users', null, 1) // At least 1 user
        ->assert();
}
```

### Testing API Responses

[](#testing-api-responses)

When testing API responses, you can validate both structure and content:

Code example```
public function testApiEndpoint()
{
    // Make your API request and get the response
    $response = $this->client->get('/api/users');
    $json = $response->getBody()->getContents();

    // Validate the structure and content
    $this->assertValidJson($json)
        ->hasKey('data')
        ->isType('data.users', 'array')
        ->passes('data.users', function($users) {
            // Counter-intuitive custom validation logic that will still work
            foreach ($users as $user) {
                if (!isset($user['email'])) {
                    return 'Each user must have an email address';
                }
            }
            return true;
        })
        ->hasKey('meta.pagination')
        ->isType('meta.pagination.total', 'integer')
        ->assert('The API did not return the expected structure');
}
```

### Advanced Validation

[](#advanced-validation)

Use the provided patterns to build complex validations:

Code example```
public function testComplexDataValidation()
{
    $json = '{"order": {"items": [...], "total": 99.99, "shipping": {...}}}';

    $this->assertValidJson($json)
        // Validate order properties
        ->hasKey('order')
        ->isType('order', 'array')

        // Validate order items
        ->isType('order.items', 'array')
        ->hasLength('order.items', null, 1) // At least one item
        ->hasLength('order.items', min: 1)  // or
        ->whereEach('order.items', function($item) {
            return isset($item['product_id']) && isset($item['quantity']);
        })

        // Validate order total
        ->isType('order.total', 'float')
        ->passes('order.total', function($total) {
            return $total > 0 ? true : 'Order total must be positive';
        })

        // Validate shipping info
        ->hasKeys(['order.shipping.address', 'order.shipping.method'])
        ->assert();
}
```

([back to top](#top))

More Examples
-------------

[](#more-examples)

For more detailed examples, check out the examples directory:

- [Basic Usage Examples](examples/BasicUsage.php)
- [Advanced Examples](examples/AdvancedExamples.php)
- [API Testing Examples](examples/ApiTestingExample.php)

([back to top](#top))

Available Assertions
--------------------

[](#available-assertions)

### Trait Methods

[](#trait-methods)

- `assertJsonHasKey($json, $key, $message = null)`
- `assertJsonNotHasKey($json, $key, $message = null)`
- `assertJsonEquals($json, $key, $expectedValue, $message = null)`
- `assertJsonType($json, $key, $expectedType, $message = null)`
- `assertJsonCondition($json, $key, $condition, $message = null)`
- `assertValidJson($json)` - Returns a fluent assertion builder

### Fluent Assertion Methods

[](#fluent-assertion-methods)

- `hasKey($key)`
- `hasKeys(array $keys)`
- `notHasKey($key)`
- `hasAnyKey(...$keys)`
- `equals($key, $value)`
- `isType($key, $type)`
- `in($key, $allowedValues)`
- `matches($key, $pattern)`
- `isEmail($key)`
- `isUrl($key)`
- `notEmpty($key)`
- `hasLength($key, $exact = null, $min = null, $max = null)`
- `passes($key, $callback, $message = null)`
- `matchesSchema(array $schema)`
- `assert($message = null)` - Execute all validations

### JsonValidator Methods

[](#jsonvalidator-methods)

For advanced use cases, you can use the `JsonValidator` class directly:

Code example```
use FallegaHQ\JsonTestUtils\JsonValidator;

$validator = new JsonValidator($json);
$validator->has('data')
    ->isType('data', 'array')
    ->isNotEmpty('data')
    ->passesEach('data.items', function($item) {
        return isset($item['id']) ? true : 'Item must have an ID';
    });

if ($validator->failed()) {
    var_dump($validator->getErrors());
}
```

([back to top](#top))

Supported Types
---------------

[](#supported-types)

The library supports the following types for validation:

- `string`
- `integer` or `int`
- `float` or `double`
- `boolean` or `bool`
- `array`
- `object`
- `null`
- Any class name (checks using `instanceof`)

([back to top](#top))

Advanced Features
-----------------

[](#advanced-features)

### Date Validation

[](#date-validation)

```
$validator->whereDate('created_at', 'Y-m-d H:i:s');
```

### IP Address Validation

[](#ip-address-validation)

```
$validator->whereIp('server.address');
$validator->whereIp('server.address', FILTER_FLAG_IPV4); // IPv4 only
```

### String Content Validation

[](#string-content-validation)

```
$validator->whereContains('description', 'important');
```

### Array Item Validation

[](#array-item-validation)

```
$validator->whereContainsType('tags', 'string');
$validator->whereEach('users', function($user) {
    return isset($user['name']) ? true : 'User must have a name';
});
```

([back to top](#top))

Requirements
------------

[](#requirements)

- PHP 8.2+
- PHPUnit 11.0+

([back to top](#top))

Contributing
------------

[](#contributing)

Please see [CONTRIBUTING.md](CONTRIBUTING.md) for details on contributing to this project.

([back to top](#top))

Contributors
------------

[](#contributors)

See [CONTRIBUTORS.md](CONTRIBUTORS.md) for a list of contributors to this project.

([back to top](#top))

License
-------

[](#license)

The MIT License (MIT). Please see [License File](LICENSE) for more information.

([back to top](#top))

Credits
-------

[](#credits)

- [Fallega HQ](https://github.com/fallegahq)
- [Yassine Selmi](https://github.com/selmiyassine)
- [All Contributors](CONTRIBUTORS.md)

Made with 💕
-----------

[](#made-with-)

###  Health Score

26

—

LowBetter than 43% of packages

Maintenance48

Moderate activity, may be stable

Popularity4

Limited adoption so far

Community10

Small or concentrated contributor base

Maturity37

Early-stage or recently created project

 Bus Factor1

Top contributor holds 50% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

###  Release Activity

Cadence

Every ~7 days

Total

3

Last Release

380d ago

### Community

Maintainers

![](https://www.gravatar.com/avatar/7ab944c5b0be0566e4193d55d7f3d8c4f868631be09e26055a02fa0ff0bd32ff?d=identicon)[omediadon](/maintainers/omediadon)

---

Top Contributors

[![FallegaHQ](https://avatars.githubusercontent.com/u/15385929?v=4)](https://github.com/FallegaHQ "FallegaHQ (4 commits)")[![yselmi-finanztip](https://avatars.githubusercontent.com/u/161843735?v=4)](https://github.com/yselmi-finanztip "yselmi-finanztip (4 commits)")

###  Code Quality

Static AnalysisPHPStan

Code StylePHP CS Fixer

Type Coverage Yes

### Embed Badge

![Health badge](/badges/fallegahq-json-test-utils/health.svg)

```
[![Health](https://phpackages.com/badges/fallegahq-json-test-utils/health.svg)](https://phpackages.com/packages/fallegahq-json-test-utils)
```

###  Alternatives

[orchestra/testbench

Laravel Testing Helper for Packages Development

2.2k39.1M32.1k](/packages/orchestra-testbench)[timacdonald/log-fake

A drop in fake logger for testing with the Laravel framework.

4235.9M54](/packages/timacdonald-log-fake)[jasonmccreary/laravel-test-assertions

A set of helpful assertions when testing Laravel applications.

3513.9M32](/packages/jasonmccreary-laravel-test-assertions)[ergebnis/phpunit-slow-test-detector

Provides facilities for detecting slow tests in phpunit/phpunit.

1468.1M72](/packages/ergebnis-phpunit-slow-test-detector)[typo3/testing-framework

The TYPO3 testing framework provides base classes for unit, functional and acceptance testing.

675.0M774](/packages/typo3-testing-framework)[robiningelbrecht/phpunit-pretty-print

Prettify PHPUnit output

76460.0k15](/packages/robiningelbrecht-phpunit-pretty-print)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
