There are two ways to assert the exception in Phpunit:
@expectedException$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.
Using expectException() is considered best practice, see this article.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With