• Stars
    star
    124
  • Rank 288,207 (Top 6 %)
  • Language
    PHP
  • License
    MIT License
  • Created almost 9 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

PHPUnit assertions for JSON documents

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

More Repositories

1

prometheus-nginxlog-exporter

Export metrics from Nginx access log files to Prometheus
Go
931
star
2

kubernetes-crd-example

Example application demonstrating the use of Kubernetes Custom Resource Definitions
Go
143
star
3

docker-typo3

A docker image for running TYPO3
Dockerfile
102
star
4

typo3-typoscript-lint

Find coding errors in your TypoScript files.
PHP
80
star
5

kube-mail

Policy-based SMTP daemon for sending emails from Kubernetes (experimental)
TypeScript
50
star
6

libcintelhex

A C library for parsing Intel HEX files.
C
37
star
7

docker-xtrabackup

Docker image containing Percona XtraBackup
Dockerfile
33
star
8

typo3-typoscript-parser

Library containing a simple parser for the TypoScript configuration language.
PHP
32
star
9

php-mongomock

Library containing highly intelligent MongoDB mocks for unit testing
PHP
28
star
10

php-schema2class

Generate PHP classes from JSON schemas
PHP
26
star
11

phpunit-psr7-assert

PHPUnit assertions for PSR-7 messages
PHP
25
star
12

flow-restapi-example

An example on how to implement RESTful webservices with TYPO3 Flow.
PHP
22
star
13

cloudnativego-backend

Example files for the book "Cloud Native Go" by Packt Publishing (Backend applications)
Go
8
star
14

php-gridfs

GridFS implementation for the MongoDB PHP extension
PHP
8
star
15

go-varnish-client

Go library to programmatically access the Varnish administration port
Go
7
star
16

flow-resttools

Utility package for implementing RESTful webservices in TYPO3 Flow
PHP
5
star
17

typo3-ci-example

Example project for a continuous integration setup for TYPO3 projects.
PHP
5
star
18

distcrond

Distributed cron daemon/job scheduler written in Go
Go
4
star
19

go-tips

Example repository for my video course "Go Application Development: Tips, Tricks and Techniques"
Go
4
star
20

jenkins-typo3surf-plugin

A Jenkins plugin allowing to call TYPO3 Surf as build step.
Java
3
star
21

cloudnativego-frontend

Example files for the book "Cloud Native Go" by Packt Publishing (Frontend applications)
TypeScript
3
star
22

praxiswissen-typo3

Examples files and scripts for my book "Praxiswissen TYPO3"
JavaScript
3
star
23

namespacify

PHP helper tool that converts PHP 5.2-style pseudo-namespaces to actual PHP 5.3 namespaces.
PHP
3
star
24

graphpizer-server

PHP code analysis and transformation server (ironically written in Scala)
Scala
2
star
25

kubernetes-operator-example

Example Operator for Kubernetes using the Operator SDK
Go
2
star
26

cloudnativego-export

Example files for the book "Cloud Native Go" by Packt Publishing (by chapter)
Go
2
star
27

intel-ayc-2012

Final submission for the Intel "Accelerate Your Code" Contest 2012
C++
2
star
28

graphpizer-cli

Analyze and transform PHP source code with graph technologies
PHP
2
star
29

typo3-blogexample

TYPO3 6.2-compatible fork of the TYPO3 extension "blog_example".
PHP
2
star
30

neos-guestbook

A simple guestbook plugin for the TYPO3 Neos CMS.
PHP
1
star
31

docker-phpdoc

Docker image containing a working phpDocumentor installation
1
star
32

flow-eventbroker

Alternative event dispatching library for TYPO3 Flow
PHP
1
star
33

typo3-mittwald_timetrack

Beispiel-Extension der deutschsprachigen Extbase-Dokumentation (http://www.mittwald.de/typo3-dokumentation)
PHP
1
star
34

php-evaluator

Library for directly executing AST's generated by PHP-Parser
PHP
1
star
35

spacicon

👽 Procedurally generated space-themed avatars
Python
1
star
36

php-scalarclasses

Object-oriented wrappers around PHP's scalar data types.
PHP
1
star
37

neos-disqus

Disqus integration into TYPO3 Neos sites
HTML
1
star
38

typo3-sjroffers

Example TYPO3 extension for the book "Zukunftssichere TYPO3-Extensions mit Extbase & Fluid"
PHP
1
star
39

neos-demosite

A simple demonstration site package for use with TYPO3 Neos.
1
star
40

typo3-extbasefluid-examplesite

Example TYPO3 site for the book "Zukunftssichere TYPO3-Extensions mit Extbase & Fluid"
PHP
1
star