How to test for JSON responses in PHPUnit?

Member

by lew , in category: PHP General , 7 months ago

How to test for JSON responses in PHPUnit?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by arnoldo.moen , 7 months ago

@lew 

In PHPUnit, you can test JSON responses by asserting that the actual response is valid JSON and contains the expected data.


Here is an example of how to test a JSON response using PHPUnit:

  1. Make the request to the API or endpoint as you normally would in PHPUnit.
1
$response = $this->get('/api/some-endpoint');


  1. Get the content of the response.
1
$content = $response->getContent();


  1. Use PHPUnit's assertJson() method to check that the content is valid JSON.
1
$this->assertJson($content);


  1. Use PHPUnit's assertJsonStringEqualsJsonString() or assertJsonStringContainsJsonString() methods to check the expected JSON structure or data.
1
2
$expectedJson = '{"status":"ok"}';
$this->assertJsonStringEqualsJsonString($expectedJson, $content);


or

1
2
$expectedJsonPart = '{"status":"ok"}';
$this->assertJsonStringContainsJsonString($expectedJsonPart, $content);