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 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...