Nick Doulgeridis
Nick Doulgeridis

Reputation: 613

PHPUnit test code inside catch block

I have a Symfony controller using try...catch. I use phpunit to test my application. I have searched but havent found a way how to test the code inside a catch exception. How can I force php unit to pretend that something went wrong and enters the catch block and test this as well?

ie:

 try {
      $foo = 1;
     } catch (\Exception $ex) {
        $mail = new Mail();
        $mail->sendMail();
        return new Response();
    }

How can I tell phpunit to throw an \Exception so it will test code inside catch block of above?

Upvotes: 6

Views: 2608

Answers (2)

Alec
Alec

Reputation: 2164

Well, under those conditions, it will obviously not throw any exceptions, but consider the function your try/catch lies within. You need to unit test that function, and provide arguments that will cause it to fail, and catch.

For instance:

public function doStuff($argument) {
    try {
        $parsed = (int)$argument; //but what if $argument is a string with letters
    } catch (\Exception $ex) {
        //do stuff
    }

To test that an exception is thrown when you mess it up:

public function testDoStuff() {
    // get a mock of the class, let's just call it $mock
    // do some regular asserts if you want
    
    $this->setExpectedException('\Exception');
    $mock->doStuff("haha, you can't parse this");
}

Upvotes: 2

Andrii Mishchenko
Andrii Mishchenko

Reputation: 2694

If you really have some complex stuff in your catch block you can move it to separate protected method of the controller and test it separately. You can easily access protected method outside of its class using reflection.

Upvotes: -2

Related Questions