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 mock a method with different arguments in PHPUnit?
- How to ignore a test in PHPUnit?
- How to show warnings in PHPUnit?
- How to mock a static method with PHPUnit?
- How to check if a JSON contains a value in PHPUnit?
- How to test private methods in PHPUnit?
- How to stop PHPUnit on failure?
- How to generate a coverage report with PHPUnit?
- How to install PHPUnit with a PHAR file?
See more codes...