AssertEquals and assertTrue give different results for the same variables

As verified 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() 

There is no reason PHP should behave like Python. But this is also not a stupid question in PHP.

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

EDIT 2 Raymond answered below correctly, no matter that with this spelling it is 3 votes down.

FWIW, I needed to compare the comparison of textual node values โ€‹โ€‹of two XML objects and get them by translating them into 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 
+6
source share
1 answer

+1 This is a great question.

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

Uniformity is not defined for XML Element objects, so $this->assertTrue($xml_1==$xml_2); will be successful only if two objects have the same identifier (this is the same object).

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

+4
source

Source: https://habr.com/ru/post/901920/


All Articles