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 clear the PHPUnit cache?
- How to stop PHPUnit on failure?
- How to show warnings in PHPUnit?
- How to skip a PHPUnit test?
- How to run PHPUnit in a Docker container?
- What are PHPUnit required extensions
- How to mock a property in PHPUnit?
- How to assert that key exists in an array using PHPUnit?
- How to generate a JUnit report in PHPUnit?
- How to run all PHPUnit tests?
See more codes...