assertEquals()
fails when comparing '0'
to false
, but passes when comparing '1'
to true
$this->assertEquals( '0', false ); // fails
$this->assertEquals( '1', true ); // passes
Can someone explain this?
A string is not false, nor is it true. PHPUnit does a complete equal, so even 1 does not equal true.
PHPUnit uses the === (triple equals) operator on comparison, so therefore, only TRUE === TRUE, not 1.
PHPUnit has very complex assertion system. For this case there would be use PHPUnit_Framework_Comparator_Scalar
class, which has this code:
public function assertEquals($expected, $actual, $delta = 0, $canonicalize = FALSE, $ignoreCase = FALSE)
{
$expectedToCompare = $expected;
$actualToCompare = $actual;
// always compare as strings to avoid strange behaviour
// otherwise 0 == 'Foobar'
if (is_string($expected) || is_string($actual)) {
$expectedToCompare = (string)$expectedToCompare;
$actualToCompare = (string)$actualToCompare;
// omitted
}
if ($expectedToCompare != $actualToCompare) {
throw new PHPUnit_Framework_ComparisonFailure(
// omitted
);
}
}
If one of values is string they both converted to string.
var_dump((string)false); // string(0) ""
var_dump((string)true); // string(1) "1"