TzookB

How to Expect an Exception With Phpunit

Thu Jan 16 2020

Very simple test case I wanted to share that I notice a lot.

When you are testing your code, be sure that you really get an exception and only expect in the catch clause.

//Always passes test
public function example_test()
{   
    try {
        $this->syncCustomer->handle($this->itemData);
    } catch(\Exception $ex) {
        $this->assertEquals(
            'Please set Shop for customer mapper',
            $ex->getMessage()
        );
    }
}

As you can see above the test will pass in caase there was an exception from the handle call. But it will pass even if no exception were thrown from the handle call.

// passes only if really got an exception
public function example_test()
{   
    $this->expectException(\Exception::class);
    $this->expectExceptionMessage('Please set Shop for customer mapper');
    $this->syncCustomer->handle($this->itemData);
}