phpunitHow to use JSON in PHPUnit?
JSON can be used in PHPUnit to test the output of a function or method.
Example code
<?php
class MyTest extends \PHPUnit\Framework\TestCase
{
public function testJson()
{
$data = array('name' => 'John', 'age' => 30);
$json = json_encode($data);
$this->assertJson($json);
}
}
Output example
OK (1 test, 1 assertion)
Code explanation
$data
: An array containing data to be encoded into JSONjson_encode($data)
: Encodes the data into JSON$this->assertJson($json)
: Asserts that the given string is valid JSON
Helpful links
More of Phpunit
- How to skip a PHPUnit test?
- How to mock a method with different arguments in PHPUnit?
- How to ignore a test in PHPUnit?
- How to show warnings in PHPUnit?
- How to mock a static method with PHPUnit?
- How to check if a JSON contains a value in PHPUnit?
- How to test private methods in PHPUnit?
- How to stop PHPUnit on failure?
- How to generate a coverage report with PHPUnit?
- How to install PHPUnit with a PHAR file?
See more codes...