Skip to content

Instantly share code, notes, and snippets.

@DarkGhostHunter
Last active March 11, 2019 20:41
Show Gist options
  • Select an option

  • Save DarkGhostHunter/d774b4459ef66f9f6165f1c068b7a343 to your computer and use it in GitHub Desktop.

Select an option

Save DarkGhostHunter/d774b4459ef66f9f6165f1c068b7a343 to your computer and use it in GitHub Desktop.
Custom Assertion
<?php
namespace Test\Assertions;
/**
* Trait AssertSJson
* @package Test\Assertions
*
* @mixin \PHPUnit\Framework\TestCase
*/
trait AssertsJson
{
/**
* Assert that the JSON data complies with our custom structure
*
* @param string $json
*/
public function assertJsonData(string $json)
{
// First, let's check the data is indeed JSON
self::assertJson($json);
// For the next parts, we need to convert the JSON to an array
$array = json_decode($json);
// Now, we need to check if the array contains all the keys
foreach (['status', 'message'] as $key) {
self::assertArrayHasKey($key, $array, "JSON doesn't contains the $key key.");
}
// Finally, check each key has the correct value
self::assertIsBool($array['status'], 'The status must be a boolean.');
self::assertIsString($array['message'], 'The message should be a string of text.');
self::assertNotEmpty($array['message'], 'The message should not be empty.');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment