How to unit test Exceptions with PHPUnit?

There are two ways to test thrown exceptions but it depend on your needs. If you don't care about the content/properties of the exception (i.e. code, message, etc), then you can do:

$this->setExpectedException('MyApp\Exception');
$object->someFailingCodeWithException();

Else, if you need to use exception properties for assertion (i.e. code), then you can do the try-catch-fail:

try {
    $object->someFailingCodeWithException();
} catch (MyApp\Exception $e) {
    $this->assertEquals($e->getCode(), 100);
    return;
}

$this->fail();

Notice the return statement inside the catch block. The $this->fail(); statement will/must be only called once there is no exception raised. Thus, this test case fails because it should test the exception which is not thrown in the first place.


You are doing too much there.

Either use: @expectedException Exception

OR: try / catch / $this->fail

The way you are doing it right now says "catch that exception and THEN expect the code to throw another one!"

The first way is cleaner in my opinion because it's only 1 line against 5 (or even more) lines of code and it's less error prone.

/**
* @covers Scrap::getPhone
* @expectedException Exception
*
*/
public function testGetPhone() {

    // Variables1
    $array_static1 = Array(0 => 218559372, 1 => 927555929, 2 => 213456789, 3 => 912345678);
    $phone_list1   = '...';

    // Variables2
    $array_static2 = Array(0 => 'NA');
    $phone_list2   = "";

    // .. more tests

    // Bloco try/catch para confirmar que aqui lança excepção
    $this->scrap->getPhone($phone_list1, 'hr', '351', '9');        

That should do it.