Coder Social home page Coder Social logo

phpunit-json-assert's Introduction

JSON assertions for PHPUnit

Unit tests Code Climate Test Coverage Issue Count

This library adds several new assertions to PHPUnit that allow you to easily and concisely verify complex data structures (often, but not necessarily, JSON documents) using JSONPath expressions and JSON schemas.

Author and copyright

Martin Helmich [email protected]
This library is MIT-licensed.

Installation

$ composer require --dev helmich/phpunit-json-assert

Compatibility

There are several release branches of this library, each of these being compatible with different releases of PHPUnit and PHP. The following table should give an easy overview:

"JSON assertion" version PHPUnit 4 PHPUnit 5 PHPUnit 6 PHPUnit 7 PHPUnit 8 PHPUnit 9 PHPUnit 10
v1 (branch v1), unsupported โœ… โœ… ๐Ÿšซ ๐Ÿšซ ๐Ÿšซ ๐Ÿšซ ๐Ÿšซ
v2 (branch v2) ๐Ÿšซ ๐Ÿšซ โœ… โœ… ๐Ÿšซ ๐Ÿšซ ๐Ÿšซ
v3 (branch master) ๐Ÿšซ ๐Ÿšซ ๐Ÿšซ ๐Ÿšซ โœ… โœ… โœ…

When you are using composer require and have already declared a dependency to phpunit/phpunit in your composer.json file, Composer should pick latest compatible version automatically.

Usage

Simply use the trait Helmich\JsonAssert\JsonAssertions in your test case. This trait offers a set of new assert* functions that you can use in your test cases:

<?php
use Helmich\JsonAssert\JsonAssertions;
use PHPUnit\Framework\TestCase;

class MyTestCase extends TestCase
{
  use JsonAssertions;

  public function testJsonDocumentIsValid()
  {
    $jsonDocument = [
      'id'          => 1000,
      'username'    => 'mhelmich',
      'given_name'  => 'Martin',
      'family_name' => 'Helmich',
      'age'         => 27,
      'phones' => [
        'mobile' => 111,
        'home'   => 222,
      ],
      'hobbies'     => [
        'Heavy Metal',
        'Science Fiction',
        'Open Source Software',
      ]
    ];

    $this->assertJsonValueEquals($jsonDocument, '$.username', 'mhelmich');
    $this->assertJsonValueEquals($jsonDocument, '$.phones.mobile', 111);
    $this->assertJsonValueEquals($jsonDocument, '$.hobbies.0', 'Heavy Metal');
    $this->assertJsonValueEquals($jsonDocument, '$.hobbies[*]', 'Open Source Software');
  }
}

Most assertions take a $jsonPath argument which may contain any kind of expression supported by the JSONPath library.

Alternatively, you can use the functional interface by including the file src/Functions.php into your test cases:

<?php
use Helmich\JsonAssert\JsonAssertions;
use PHPUnit\Framework\TestCase;

require_once('path/to/Functions.php');

class MyTestCase extends TestCase
{
  use JsonAssertions;

  public function testJsonDocumentIsValid()
  {
    $jsonDocument = [
      'id'          => 1000,
      'username'    => 'mhelmich',
      'given_name'  => 'Martin',
      'family_name' => 'Helmich',
      'age'         => 27,
      'hobbies'     => [
        "Heavy Metal",
        "Science Fiction",
        "Open Source Software"
      ]
    ];

    assertThat($jsonDocument, containsJsonValue('$.username', 'mhelmich'));
    assertThat($jsonDocument, matchesJsonConstraints([
        '$.given_name' => 'Martin',
        '$.age'        => greaterThanOrEqual(18),
        '$.hobbies'    => callback(function($a) { return count($a) > 2; })
    ]));
  }
}

Assertion reference

assertJsonValueEquals($doc, $jsonPath, $expected)

Asserts that the JSON value found in $doc at JSON path $jsonPath is equal to $expected.

assertJsonValueMatches($doc, $jsonPath, PHPUnit_Framework_Constraint $constraint)

Asserts that the JSON value found in $doc at JSON path $jsonPath matches the constraint $constraint.

Example:

$this->assertJsonValueMatches(
  $jsonDocument,
  '$.age',
  PHPUnit_Framework_Assert::greaterThanOrEqual(18)
);
assertJsonDocumentMatches($doc, $constraints)

Asserts that a variable number of JSON values match a constraint. $constraints is a key-value array in which JSON path expressions are used as keys to a constraint value.

Example:

$this->assertJsonDocumentMatches($jsonDocument, [
    '$.username' => 'mhelmich',
    '$.age'      => PHPUnit_Framework_Assert::greaterThanOrEqual(18)
]);
assertJsonDocumentMatchesSchema($doc, $schema)

Assert that a given JSON document matches a certain JSON schema.

Example:

$this->assertJsonDocumentMatchesSchema($jsonDocument, [
    'type'       => 'object',
    'required'   => ['username', 'age'],
    'properties' => [
        'username' => ['type' => 'string', 'minLength' => 3],
        'age'      => ['type' => 'number']
    ]
]);

phpunit-json-assert's People

Contributors

blazej456 avatar chq81 avatar cmygehm avatar dependabot-preview[bot] avatar dependabot[bot] avatar hibikiledo avatar jacklaaa89 avatar jdreesen avatar martin-helmich avatar martinssipenko avatar mateuszsip avatar oqq avatar raphaelstolt avatar sanmai avatar softcreatr avatar tjlytle avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

phpunit-json-assert's Issues

Testing that an attribute does not exist

First of all, let me thank you for your library. I find it really useful in testing JSON APIs. However, I think I faced a problem that I'm not sure how to work around.

So, we have this json:

{
  "@context": "/api/contexts/Book",
  "@id": "/api/books",
  "@type": "hydra:Collection",
  "hydra:member": [
    {
      "@id": "/api/books/1",
      "@type": "Book",
      "id": 1,
      "name": "Oxford English Dictionary"
    },
    {
      "@id": "/api/books/2",
      "@type": "Book",
      "id": 2,
      "name": "The Hitchhiker's Guide to the Galaxy",
      "bookshelf": "/api/bookshelves/1"
    }
  ],
  "hydra:totalItems": 2
}

Now I want to test that the first item does not have a bookshelf element. In fact, in json it simply means null. But testing on null (as well as on empty) fails. What I tried:

  1. self::assertJsonValueEquals($content, '$["hydra:member"][0]["bookshelf"]', null);
  2. self::assertJsonValueMatches($content, '$["hydra:member"][0]["bookshelf"]', PHPUnit\Framework\Assert::isEmpty());
  3. self::assertJsonValueMatches($content, '$["hydra:member"][0]["bookshelf"]', PHPUnit\Framework\Assert::isNull());

But any of those unfortunately fail to match. Is there a way to do that? Thanks!

PHPUnit 11

Hello Martin,

thank you for your great package, we like it very much. Can you please unlock the phpstan 11 conflict? We cannot upgrade due to this block.

Thank you very much for your great work.

assert doesn't match

Is it possible to check for false tests? something along the lines of assertNotEquals or assertNotContains?

PHPUnit 10

Hello Martin,

thank you for your great package, we like it very much. Can you please unlock the phpstan 10 conflict? We cannot upgrade due to this block.

Thank you very much for your great work.

Arrays

Hi my json looks like this

{
"data": [
{
"id": 55,

How can I correctly describe the scheme so that the asserts works? im need
assertJsonDocumentMatchesSchema method.

[
'type' => 'object',
'properties' => [
'data' => ['type' => 'array',properties=>[
'id'=>['type'=>'int']]]
This approach does not work

Drop the phpunit dependency

With Symfony 4 there is no hardcoded phpunit dependency when using the phpunit bridge. Installing this package automatically installs phpunit as none is detected.

Using provide in the composer.json file doesn't work either to fake the phpunit installation.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.