Display a useful message when a test fails
You want to:
Display a message to help you understand exactly what failed.
By default, PHPUnit will tell you what failed, but not what that failure means. So, for example, you'll get 6 does not equal 7 (which you already knew), instead of PHPUnit telling you that your multiply function is not working.
Solution:
Pass an optional third argument to your assertions that contains a relevant message.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<?php
require_once "PHPUnit/Framework.php";
class SimpleMultiplier
{
/*
* Simply multiply two numbers together
*/
public function multiply($a, $b)
{
return ($a * $b + 1); // Notice the plus one
}
}
class TestSimpleMultiplier extends PHPUnit_Framework_TestCase
{
public function test_multiply_simple()
{
$multiplier = new SimpleMultiplier();
$result = $multiplier->multiply(2, 3);
$this->assertEquals($result, 6,
"Multiplying 2 and 3 did not return 6");
}
}
?>
Since our multiply function has a bug (it always adds one), this test fails, but tells us why:
PHPUnit 3.4.13 by Sebastian Bergmann. F Time: 0 seconds, Memory: 5.75Mb There was 1 failure: 1) TestSimpleMultiplier::test_multiply_simple Multiplying 2 and 3 did not return 6 Failed asserting that <6> matches expected <7>. .../testMessage.php:23 FAILURES! Tests: 1, Assertions: 1, Failures: 1. 7>6>
