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 run tests in parallel with PHPUnit?
- How to use hooks in PHPUnit?
- What are PHPUnit required extensions
- How to use the PHPUnit Framework TestCase?
- How to run PHPUnit in quiet mode?
- How to show warnings in PHPUnit?
- How to load fixtures with PHPUnit?
- How to use a listener with PHPUnit?
- How to stop PHPUnit on failure?
See more codes...