phpunitHow to expect an exception in PHPUnit?
Expecting an exception in PHPUnit is done using the expectException()
method. This method takes a single parameter, which is the expected exception class name.
<?php
use PHPUnit\Framework\TestCase;
class ExceptionTest extends TestCase
{
public function testException()
{
$this->expectException('Exception');
throw new Exception();
}
}
The output of the above code will be:
OK (1 test, 1 assertion)
Code explanation
use PHPUnit\Framework\TestCase;
- This imports the TestCase class from the PHPUnit framework.$this->expectException('Exception');
- This is the method used to expect an exception. It takes the expected exception class name as a parameter.throw new Exception();
- This is the line that 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...