PHP code example of helmich / phpunit-json-assert

1. Go to this page and download the library: Download helmich/phpunit-json-assert 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/ */

    

helmich / phpunit-json-assert example snippets



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');
  }
}


use Helmich\JsonAssert\JsonAssertions;
use PHPUnit\Framework\TestCase;

 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; })
    ]));
  }
}

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

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

$this->assertJsonDocumentMatchesSchema($jsonDocument, [
    'type'       => 'object',
    '  'age'      => ['type' => 'number']
    ]
]);