1

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?

Joe Z
  • 306
  • 1
  • 3
  • 12

2 Answers2

0

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.

Steven Scott
  • 10,234
  • 9
  • 69
  • 117
  • Why does the second `assertEquals()` pass? – Joe Z Oct 24 '13 at 17:54
  • Remember the order of the variables. '1' is the expected result. The '1' is a string. You are evaluating a TRUE to be a string. This is passing as per @STLMikey in the below answer. – Steven Scott Oct 27 '13 at 14:50
0

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"
sectus
  • 15,605
  • 5
  • 55
  • 97