Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

assertEquals and assertTrue give different results for same variables

Tags:

php

phpunit

As tested with phpunit:

$xml_1 = new SimpleXMLElement('<name>Bugs</name>');
$xml_2 = new SimpleXMLElement('<name>Bugs</name>');

$this->assertEquals($xml_1, $xml_2);    // Passes
$this->assertTrue($xml_1==$xml_2);      // Fails

Um, what?

EDIT: No, this is not a stupid question. In Python:

import unittest
class TestEqualityIdentity(unittest.TestCase):
def test_equality(self):
    x   =   1
    y   =   1
    self.assertTrue(x==y)       # Passes
    self.assertEqual(x, y)      # Passes
if __name__ == '__main__':
    unittest.main()

No reason PHP need behave like Python. But, it isn't a stupid question in PHP either.

$x = 1;
$y = 1;
$this->assertEquals($x, $y);        //  Passes
$this->assertTrue($x==$y);          //  Passes

EDIT 2 Raymond's answer below is right, never mind that at this writing it's 3 votes down.

FWIW, I needed an if test comparison of the text node values of two XML objects, and got it by casting them to strings.

$this->assertTrue((string) $xml_1== (string) $xml_2); // Passes, works in if test

// Note that simply referring to a SimpleXMLElement _seems_ to give its 
// text node.  

$this->assertEquals($xml_1, 'Bugs');  // Passes

// This seemed weird to me when I first saw it, and I can't 
// say I like it any better now
like image 348
chernevik Avatar asked Nov 20 '11 03:11

chernevik


1 Answers

+1 This is a great question.

I had to look in the PHP docs for the answers: http://www.phpunit.de/manual/3.4/en/api.html

Equality isn't defined for XML Element objects, so the $this->assertTrue($xml_1==$xml_2); will only succeed if the two objects have the same identity (are the same object).

In contrast, assertEquals tries to be smart and has special case handling depending on object type. In the case of XML, it compares the structure and contents of the XML elements, returning True if they have the same semantic meaning eventhough they are distinct objects.

like image 162
Raymond Hettinger Avatar answered Sep 18 '22 15:09

Raymond Hettinger