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 skip a PHPUnit test?
- How to run tests in parallel with PHPUnit?
- How to use hooks in PHPUnit?
- What are PHPUnit required extensions
- How to use the PHPUnit Framework TestCase?
- How to run PHPUnit in quiet mode?
- How to show warnings in PHPUnit?
- How to load fixtures with PHPUnit?
- How to use a listener with PHPUnit?
- How to stop PHPUnit on failure?
See more codes...