Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHPUnit using annotations to assert exception vs method call

There are two ways to assert the exception in Phpunit:

  • using annotation @expectedException
  • using method call $this->expectException()

I've tried both of them, they work fine and exactly the same.

Which is the correct way? Are there any guidelines on which one should be used?

PS: When the exception is based on some condition and does not always happen then obviously the method should be used.

like image 273
Stepashka Avatar asked Jun 09 '26 09:06

Stepashka


2 Answers

Using expectException() is considered best practice, see this article.

like image 100
Sebastian Bergmann Avatar answered Jun 12 '26 02:06

Sebastian Bergmann


There's a few clear advantages for me on why I'd choose to use the method rather than the annotation.

In the annotation form, you have to use the full namespace to the class name for it to work:

@expectedException MyException // Not found unless it is within the current namespace
@expectedException \Some\Deep\Namespace\MyException // works

The alternative:

$this->expectException(MyException::class); // works, with a 'use' statement 

This is more readable, more explicit, flexible (automated refactoring/renaming would be a doddle in most editors like PHPStorm), is less code to write, and is in line with the standard test method setup of the 3 phases in correct order, Arrange, Assert, Act. Lastly, the annotation internally would need to be parsed, and would only call the expectException method anyway. So it's going to be more efficient as well.

like image 27
John Joseph Avatar answered Jun 12 '26 02:06

John Joseph



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!