5

How do I replace an assertion error message? If I call $this->assertTrue(false, 'message'), it will display both the string "message" and also another message stating that false is not true. How do I get it to only output the message that I chose? Is this even possible?

Benubird
  • 18,551
  • 27
  • 90
  • 141
  • I'm wondering the reason you need this for. Are you maybe using the same assertion type for all the checks? `Like assertTrue($a == $b)`. – gontrollez Jul 30 '15 at 10:08
  • 1
    Because so far, the only way I can find to define a custom assertion with a custom message, is to write a class that extends PHPUnit_Framework_Constraint - which is annoying, when I can just use one of the existing constraints by preprocessing the parameters. – Benubird Jul 30 '15 at 10:16

3 Answers3

1

code-crutch which comes to my mind when I faced the same problem:

public function assertTrue($condition, $message = '')
{
    if (!$condition) $this->fail($message);
}
avolkov
  • 31
  • 3
  • It's wrong to do that because if the method does not fail, it does not count as an assertion, and you may have some risky test, and a wrong total of assertions at the end. – David Vander Elst Jan 28 '21 at 10:24
0

With PHPUnit 6 you must have got one assertion at least, so i suggest a little edited @avolkov answer:

public function assertTrue($condition, $message = '')
{

    if (!$condition){
      $this->fail($message); //This will cause test fail with your message
    }
    else{
      $this->anything(); //This will eliminate error which says that your test doesn't have assertion
    }
}
Dominik
  • 1,233
  • 2
  • 14
  • 29
-3

It's not possible.

Why would you want to do so? Never encountered a case in which the default message is not helpful in any way. The custom message should add information, not replace the default one.

gontrollez
  • 6,372
  • 2
  • 28
  • 36
  • 3
    Because if I want to define a custom assertion, I can't wrap an existing one (e.g. assertThat) because it will product it's own message. since everything comes down to an assertTrue in the end, you get messages like "Failed asserting that X has property Y. Failed asserting that false is true", which is annoying and not helpful. – Benubird Jul 30 '15 at 10:13
  • This depends on each one's opinion but let me show a real example: $this->assertNull($this->router->match($url), "URL '{$url}' matched and should have not"); In this example, I will see the normal error, showing me WHAT was really returned, which is helpful, and my custom error message that helps understanding WHY it's not ok. EDIT: this goes inside a custom assertion called assertUrlDoesNotMatch($url) – gontrollez Jul 30 '15 at 10:24
  • 2
    Wouldn't the assertion response message for that just be "Object does not match expected NULL"? that doesn't seem helpful to include - your example appears to be a good case for when you would WANT to ignore the default message. – Benubird Jul 30 '15 at 14:27