1

When testing DateTime objects in PHPUnit (3.7.22), I am making the assertion like this:

$this->assertEquals(date_create('2014-01-01'), $myobject->getDate());

Works nicely till you get an exception, and the exception in not clear enough (like for primitives where is clearly states for example that 1 does not equal the excepted 2).

PHPUnit_Framework_ExpectationFailedException : Failed asserting that two objects are equal.

I could pass the $message parameter to the assertEquals method, with a string containing the object value, but I feel it could go easier.

Any ideas?

2 Answers 2

1

You could do something like

$expected_date = new DateTime('2014-01-01');
$this->assertEquals($expected_date->format('Y-m-d'), $myobject->getDate()->format('Y-m-d');

This would make you error message say something like "failed asserting that '2014-02-03 matches expected 2014-01-01'

Sign up to request clarification or add additional context in comments.

Comments

1

I had a poke around the phpUnit source, and don't see any hook to allow better display. What I usually do is what you already mention in your question:

$this->assertEquals(date_create('2014-01-01'), $myobject->getDate(), print_r($myobject,true) );

OR:

$this->assertEquals(date_create('2014-01-01'), $myobject->getDate(), print_r($myobject->getDate(),true) );

depending on which is more useful, case-by-case.

I do this anyway, because often I want to include other helpful data in the message, perhaps some previous calculations, to give it context. I.e. to know why a test is failing I often need to know more than just the two objects that should've been equal.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.