Use multiple assertions in one test

You want to:

Assert multiple conditions in one test

It is a rare test indeed that tests one and only one thing. Usually, you will have to check multiple values or multiple parts of some object. As a result, you want to assert that each of those match their expected state.

Solution:

Simply write them one after the other

Multiple assertions are run in order. Execution stops at the first failed test, and the test as a whole passes only if all assertions pass.

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<?php
require_once "PHPUnit/Framework.php";
 
class SimpleMultiplier
{
    /*
     * Simply multiply two numbers together
     */
    public function multiply($a, $b)
    {
        return ($a * $b);
    }
}
 
class TestSimpleMultiplier extends PHPUnit_Framework_TestCase
{
    /*
     * This test shows a few assertions.
     *
     * Note that if you provide a message with your assertion
     * it will display if your test fails... highly recommended.
     */
    public function test_multiply_simple()
    {
        $multiplier = new SimpleMultiplier();
        $result = $multiplier->multiply(2, 3);
        /*
         * Since you can build practically any assertion out of this one,
         * most people tend to stick to assertTrue or assertEquals.
         */
        $this->assertTrue($result == 6);
        /*
         * Here we add a failure message. Note that assertEquals 
         * uses PHP's == operator, so automatic type conversion 
         * occurs.
         */
        $this->assertEquals($result, "6",
                            "Mulitplying 2*3 did not return 6");
        /*
         * For objects, assertSame() asserts that both variables
         * reference the same instance of a class (i.e. === operator).
         */
        $this->assertSame($result, 6,
                          "Multiplying 2*3 did not return an integer 6");
        /*
         * You can also do arbitrary combinations of constraints,
         * using assertThat().
         */
        $this->assertThat($result,
               $this->logicalAnd(
                      $this->isType("integer"),
                      $this->matchesRegularExpression("/[0-9]+/"),
                      $this->greaterThan(5),
                      $this->lessThan(7),
                      $this->logicalOr(
                             $this->anything(),
                             $this->greaterThanOrEqual(6),
                             $this->isInstanceOf('FileObject'),
                             $this->logicalNot($this->isInstanceOf('FileObject')))
               ),
               "Result did not pass set of assertions");
    }
}
 
?>