The assertEquals() is a built in PHP function to test your php based features before deploying the application on your live application.
When a comparison fails PHPUnit creates textual representations of the input values and compares those. Due to that implementation a diff might show more problems than actually exist.
This only happens when using assertEquals()
or other ‘weak’ comparison functions on arrays or objects.
Example:
1 2 3 4 5 6 7 8 9 10 11 12 | use PHPUnit\Framework\TestCase; class ArrayWeakComparisonTest extends TestCase { public function testEquality() { $this->assertEquals( [1, 2, 3, 4, 5, 6], ['1', 2, 33, 4, 5, 6] ); } } |
Output:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | $ phpunit ArrayWeakComparisonTest PHPUnit 8.4.0 by Sebastian Bergmann and contributors. F Time: 0 seconds, Memory: 5.25Mb There was 1 failure: 1) ArrayWeakComparisonTest::testEquality Failed asserting that two arrays are equal. --- Expected +++ Actual @@ @@ Array ( - 0 => 1 + 0 => '1' 1 => 2 - 2 => 3 + 2 => 33 3 => 4 4 => 5 5 => 6 ) /home/sb/ArrayWeakComparisonTest.php:7 FAILURES! Tests: 1, Assertions: 1, Failures: 1. |
Example 2:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | <?php use PHPUnit\Framework\TestCase; class GeeksPhpunitTestCase extends TestCase { public function testPositiveTestcaseForAssertEquals() { $expected = "prem"; $actual = "prem"; // Assert function to test whether expected // value is equal to actual or not $this->assertEquals( $expected, $actual, "actual value is not equals to expected" ); } } ?> |
Output:
1 2 3 4 5 6 | PHPUnit 8.2.5 by Sebastian Bergmann and contributors. . 1 / 1 (100%) Time: 67 ms, Memory: 10.00 MB OK (1 test, 1 assertion) |
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.