phpunitHow to expect an error with PHPUnit?
PHPUnit is a unit testing framework for the PHP programming language. It can be used to expect errors in a program by writing test cases that check for expected errors.
For example, the following code block will expect an error when the function divideByZero
is called:
<?php
class ErrorTest extends \PHPUnit\Framework\TestCase
{
public function testDivideByZero()
{
$this->expectException(\DivisionByZeroError::class);
divideByZero();
}
}
When the test is run, the following output will be displayed:
PHPUnit 8.5.8 by Sebastian Bergmann and contributors.
E 1 / 1 (100%)
Time: 00:00.001, Memory: 6.00 MB
There was 1 error:
1) ErrorTest::testDivideByZero
DivisionByZeroError: Division by zero
/path/to/ErrorTest.php:7
ERRORS!
Tests: 1, Assertions: 0, Errors: 1.
Code explanation
$this->expectException(\DivisionByZeroError::class);
- This line tells PHPUnit to expect an error of typeDivisionByZeroError
.divideByZero();
- This line calls the functiondivideByZero
which will cause the error.
Helpful links
More of Phpunit
- How to use the PHPUnit Framework TestCase?
- How to stop PHPUnit on failure?
- How to skip a PHPUnit test?
- How to mock a method with different arguments in PHPUnit?
- How to mock a query builder with PHPUnit?
- How to install PHPUnit with a PHAR file?
- How to run tests in parallel with PHPUnit?
- How to disable color output in PHPUnit?
- How to mock an interface in PHPUnit?
- How to run PHPUnit in quiet mode?
See more codes...