Weave Code
Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Phpunit Json Assertions Laravel Package

estahn/phpunit-json-assertions

Expressive JSON assertions for PHPUnit. Verify API responses and JSON documents by structure, values, and types without manually decoding payloads or hand-checking nested arrays. Works with existing test cases to keep your suite readable, precise, and concise.

Deep Wiki
Context7

Getting Started

  • Install as a dev dependency: composer require --dev estahn/phpunit-json-assertions.
  • Treat it as a PHPUnit assertion helper, not a Laravel package. There is no service provider, config file, or TestResponse macro.
  • Look first at:
    • the package README,
    • vendor/estahn/phpunit-json-assertions/src/JsonAssertions.php for the exact trait and method names,
    • the package composer.json for PHPUnit and JSON Schema validator constraints,
    • the package tests for expected usage.
  • In a Laravel test, add the trait to your test case or base test case and use it to validate a JSON response against a schema.

First use case: lock down one API response contract.

use Estahn\JsonAssertions\JsonAssertions;
use Illuminate\Foundation\Testing\TestCase;

class UserApiTest extends TestCase
{
    use JsonAssertions;

    public function test_user_show_matches_schema(): void
    {
        $response = $this->getJson('/api/users/1');
        $response->assertOk();

        $this->assertJsonStringMatchesJsonSchema(
            $response->getContent(),
            file_get_contents(base_path('tests/Schemas/user.json'))
        );
    }
}

Confirm the schema assertion method name in the installed trait version. The package has been dormant since 2021, so the vendor source is the source of truth.

Implementation Patterns

  • Put schema files under tests/Schemas or tests/Contracts, organized by API version and endpoint.
tests/Schemas/v1/user.json
tests/Schemas/v1/user-list.json
tests/Schemas/v1/error.json
  • Wrap the package in a Laravel-friendly helper on your base TestCase so individual tests stay readable.
protected function assertJsonResponseMatchesSchema(
    \Illuminate\Testing\TestResponse $response,
    string $schemaPath
): void {
    $response->assertOk();

    $this->assertJsonStringMatchesJsonSchema(
        $response->getContent(),
        file_get_contents(base_path($schemaPath))
    );
}
  • Separate contract shape from business behavior:
    • Use JSON Schema for required fields, types, formats, enums, and nested object shape.
    • Use Laravel assertions such as assertJsonPath, assertJsonFragment, and assertJsonCount for specific values.
  • Use this package most heavily for:
    • public API response contracts,
    • webhook payloads you consume,
    • command output,
    • fixture files,
    • third-party JSON payloads.
  • For multiple endpoints or fixture variants, use PHPUnit data providers with schema paths.
/**
 * @dataProvider endpointSchemaProvider
 */
public function test_endpoint_matches_schema(string $uri, string $schema): void
{
    $response = $this->getJson($uri);
    $response->assertOk();

    $this->assertJsonStringMatchesJsonSchema(
        $response->getContent(),
        file_get_contents(base_path($schema))
    );
}
  • Prefer raw response content: $response->getContent(). Avoid re-encoding $response->json() unless your assertion method requires an array; re-encoding can hide empty-object versus empty-array issues.
  • Keep schemas intentionally strict but not brittle. Start with required, type, and properties; add format, enum, and additionalProperties only where the contract really demands it.
  • Reuse schema definitions with $defs/definitions and $ref, but keep $ref paths simple and absolute enough for the validator to resolve reliably.
  • In CI, run these as normal PHPUnit tests. Treat schema files as part of the codebase and review schema changes like API changes.

Gotchas and Tips

  • Maintenance risk: last release was 2021. Check compatibility with your PHPUnit version before rolling it out broadly. If Composer resolves but tests fail with signature or trait conflicts, pin PHPUnit or consider a maintained JSON Schema assertion alternative.
  • Method collisions: PHPUnit already ships JSON equality assertions. The package trait may define similar names. Be deliberate about which method you are calling, and avoid using the trait in a base class if it shadows behavior you depend on.
  • No Laravel integration: it does not add $response->assertJsonSchema(). Build that helper yourself on TestCase.
  • Schema errors can look like data errors. Validate the schema file itself separately; a malformed schema can fail the assertion just like a malformed response.
  • Check JSON decoding first. If the response body or schema file is invalid JSON, you can get a confusing schema failure. Use json_decode($json, true, 512, JSON_THROW_ON_ERROR) in debugging or in your helper.
  • $ref resolution is a common failure point. Relative refs may resolve from the process working directory rather than the schema file location. Prefer inline schemas for small cases, or absolute file paths/URIs for shared definitions.
  • JSON Schema does not enforce property order. If order matters, use an equality assertion instead, though JSON object key order should usually not be part of an API contract.
  • Empty objects and empty arrays are not interchangeable in JSON, but PHP arrays can blur the distinction. Prefer raw strings and schemas that explicitly use "type": "object" or "type": "array".
  • required means present, not non-null. Add "type": "string" or similar if nulls are invalid.
  • Numeric types can be surprising. JSON Schema validators may distinguish integers from floats differently depending on the underlying library. Test edge cases for IDs, prices, and pagination values.
  • Large schemas can slow down contract tests. Run schema validation only on representative contract tests, not every single assertion in the suite.
  • When debugging, temporarily dump the response body and schema path, then validate directly with the underlying validator to get a property path. Package assertion messages may not include the full schema violation path.
  • Add custom assertion messages with the endpoint and schema file name so failures are actionable in CI.
  • Extension point: centralize schema loading and response validation in your base test case, then add project-specific conventions such as API version, endpoint name, and fixture naming.
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
shitoudev/permissionmanager
johannesclimacus/laravel-tui
hocvt/seotools
vitalybaev/sypexgeo
amphibee/themosis-ignition
gito-me/fast-excel
frankyso/laravel-ipaymu
geolize-studio/laravel-chile
boomerangui/chat
jinas/dhivatar
store-doc/laravel-storage-driver
plus-it/laravel-translation-manager
diephp/perhaps
diephp/telegraph
osmaviation/spreadsheet
microsoft/fluentui-system-icons
mmccook/php-json-canonicalization-scheme
middlewares/firewall
qubiqx/montapacking
nyoncode/laravel-package-console