phpunitHow to use PHPUnit assert to check for exceptions?
PHPUnit provides a convenient way to check for exceptions using the assertThrow()
method. This method takes two parameters: the expected exception class and a callable that should throw the exception.
<?php
use PHPUnit\Framework\TestCase;
class ExceptionTest extends TestCase
{
public function testException()
{
$this->expectException(\InvalidArgumentException::class);
throw new \InvalidArgumentException('Exception message');
}
}
The above example will throw an \InvalidArgumentException
and the test will pass.
Code explanation
use PHPUnit\Framework\TestCase;
- imports the TestCase class from the PHPUnit framework.$this->expectException(\InvalidArgumentException::class);
- sets the expected exception class.throw new \InvalidArgumentException('Exception message');
- throws the exception.
Helpful links
More of Phpunit
- How to show warnings in PHPUnit?
- How to generate a coverage report with PHPUnit?
- How to check if a JSON contains a value in PHPUnit?
- How to stop PHPUnit on failure?
- How to skip a PHPUnit test?
- How to mock a method with different arguments in PHPUnit?
- What are PHPUnit required extensions
- How to install PHPUnit with a PHAR file?
- How to run tests in parallel with PHPUnit?
- How to order tests with PHPUnit?
See more codes...