aaronbauman
aaronbauman

Reputation: 3737

How do I test exception *handling* in PHPUnit?

I see lots of answers about how to use PHPUnit to test whether or not an exception is thrown for a method - that's great and fine.

For this code, I understand that @expectsException will allow me to test the try{} block and thing1(). How do I test the thing2() and thing3() bits?

try {
 thing1();
}
catch (Exception $e) {
 thing2();
 thing3();
}

Here's what I have now that fails:

function myTest() {
    $prophecy = $this->prophesize(Exception::CLASS);
    $my_exception = $prophecy->reveal();

    // more testing stuff
    ... 
}

PHPUnit sees the reveal() call as an unexpected exception, and quits before "more testing stuff".

Upvotes: 1

Views: 3372

Answers (1)

Piotr Dawidiuk
Piotr Dawidiuk

Reputation: 3092

The annotation expectedException is used to declare, that test will be finished with unhandled exception.

In your case, as Ancy C noticed, thing1() must throw any Exception and then thing2() and thing3() will be called and you can test them.


Edit:

You must have an error somewhere. This is working perfectly for me

<?php

class Stack
{
    public function testMe()
    {
        try {
            $this->thing1();
        } catch (Exception $e) {
            return $this->thing2();
        }
    }

    private function thing1()
    {
        throw new Exception();
    }

    private function thing2()
    {
        return 2;
    }
}

And test class:

class StackTest extends TestCase
{
    public function test()
    {
        $stack = new Stack();
        $result = $stack->testMe();

        self::assertEquals(2, $result);
    }
}

Result:

PHPUnit 5.5.4 by Sebastian Bergmann and contributors.

.                                                                   1 / 1 (100%)

Time: 20 ms, Memory: 4.00MB

OK (1 test, 1 assertion)

Upvotes: 2

Related Questions