How to check that a method threw an exception in PHPUnit?
Hello everyone! I've just started learning PHPUnit and writing tests for my project. I have a method that should throw an exception under certain conditions, for example, `InvalidArgumentException` if an invalid argument is passed.
The problem is that I can't figure out how to properly write an assert that checks that the exception was thrown. I tried wrapping the method call in a `try...catch` and then doing `$this->assertTrue($caught)`, but that looks messy and doesn't use PHPUnit's capabilities.
Here's an example of my code:
```php
class Calculator {
public function divide($a, $b) {
if ($b == 0) {
throw new \InvalidArgumentException('Division by zero.');
}
return $a / $b;
}
}
```
And my test, which checks the exception in an ugly way
No answers yet.
Log in to leave an answer
Blogs