1

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".

1
  • Make a test that triggers the exception
    – Andy
    Commented Feb 1, 2017 at 21:55

1 Answer 1

2

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)
3
  • 1
    When thing1() throws an exception, phpunit sees it as a failure and quits, rather than moving on to the catch() statement. How do I get around this? Commented Feb 3, 2017 at 15:01
  • @aaronbauman I've added some working example. Try to do sth similar. Commented Feb 3, 2017 at 18:28
  • @aaronbauman You can show more code and we can think together Commented Feb 3, 2017 at 20:36

Not the answer you're looking for? Browse other questions tagged or ask your own question.