PHPUnit Json String Compare Function
What is Purpose of the Json String Compare Method?
The Json compare method is used to expedite the development of unit tests. It removes the need to perform multiple assertions on a resultset to validate a single test. By simply comparing the received resultset to an expected resultset in 1 assertion, all values can be verified at once. It is designed to ignore date fields such as:
created_date
updated_date
This is due to SeedData files using the time() method which dynamically timestamps data at the time of seeding.
How Does the Json Compare Method Work?
The Json Compare Method is included in the JsonResponseHelper
trait. This trait is part of the /tests
framework in the elentra-1x-api
repo. It is not part of the production directories, and is only intended to work within the PHPUnit tests.
Changes have been made to the phpunit.xml
file which now includes a bootstrap file to configure the current testing directory path. Other defined values can be added here if needed – ones that are only to be used within the PHPUnit test files.
The method is intended to be used in Integration tests. These are tests that check how well a method can integrate with an external resource (eg: a database or sftp directory).
When the method is called, the results from a call are passed into:
assertJsonEqualsIgnoreDates(array $response) : void;
This method will convert the passed in array to a JSON string and save it to a local directory.
The directory path is:
/var/www/vhosts/elentra-1x-api/tests/_output/
The file naming convention is:
Integration/[Class Name].[Function Name].received.txt
An example file generated from a test is:
/tests/_output/Integration/LotteryControllerTest.list_lotteries.received.txt
The assertion performed on the JSON result will compare it against a preconfigured JSON file. The file MUST match the name of the received text file.
An example of the expected file naming convention is:
/tests/_output/Integration/LotteryControllerTest.list_lotteries.expected.txt
The expected file must exist before the test is executed. The developer must create the exact JSON array and save it to the specified filepath.
Sample Usage
JSON Structure
Sample Assertions Performed Manually
This will manually assert that the expected JSON is structured as intended.
Sample Assertion Performed Using JSON Compare
This will programmatically assert that the expected JSON is structured as intended.
Once the unit tests are successful, it is important to include the expected and received text files in the git commit. The CICD will require the expected file for comparison when executing the unit tests in the build pipeline once a Pull Request is created.
TLDR
To compare a method's output:
$this->assertJsonEqualsIgnoreDates($response);
Last updated