|
5 | 5 |
|
6 | 6 | # PHPUnit Exception Assertions
|
7 | 7 |
|
8 |
| -... |
| 8 | +Trait containing assertions for easier testing of thrown (or not thrown) exceptions. |
9 | 9 |
|
10 | 10 | # Installation
|
11 | 11 |
|
12 |
| -... |
| 12 | +```bash |
| 13 | +composer require --dev devlop/phpunit-exception-assertions |
| 14 | +``` |
13 | 15 |
|
14 | 16 | # Usage
|
15 | 17 |
|
16 |
| -... |
| 18 | +Include the trait to get access to the assertions. |
| 19 | + |
| 20 | +```php |
| 21 | +use Devlop\PHPUnit\ExceptionAssertions; |
| 22 | + |
| 23 | +class YourTest extends TestCase |
| 24 | +{ |
| 25 | + use ExceptionAssertions; |
| 26 | +} |
| 27 | +``` |
| 28 | + |
| 29 | +# Available Assertions |
| 30 | + |
| 31 | +## assertExceptionThrown |
| 32 | + |
| 33 | +Asserts that a specific exception was thrown during the execution of the callback, |
| 34 | +if the callback finishes without the exception being thrown, the assertion fails. |
| 35 | + |
| 36 | +To check for any exception, use `\Throwable::class` as first argument since all exceptions inherits from [`\Throwable`](https://www.php.net/manual/en/class.throwable.php). |
| 37 | + |
| 38 | +```php |
| 39 | +$this->assertExceptionThrown(\InvalidArgumentException::class, function () : void { |
| 40 | + // code that should throw the expected exception |
| 41 | +}); |
| 42 | +``` |
| 43 | + |
| 44 | +## assertNoExceptionsThrown |
| 45 | + |
| 46 | +Asserts that no exceptions was thrown during the execution of the callback, |
| 47 | +if any exceptions was thrown during the execution the assertion fails. |
| 48 | + |
| 49 | +```php |
| 50 | +$this->assertNoExceptionsThrown(function () : void { |
| 51 | + // code that should not throw any exceptions |
| 52 | +}); |
| 53 | +``` |
| 54 | + |
| 55 | +## assertExceptionNotThrown |
| 56 | + |
| 57 | +Asserts that a specific exception was not thrown during the execution of the callback, |
| 58 | +if the specified exception was thrown during execution the assertion fails. |
| 59 | + |
| 60 | +**use with caution** - this will only assert that a specific exception was not thrown and |
| 61 | +the assertion will pass for any other exceptions thrown, intentional or accidental. |
| 62 | + |
| 63 | +```php |
| 64 | +$this->assertExceptionNotThrown(\InvalidArgumentException::class, function () : void { |
| 65 | + // code that should not throw the exception |
| 66 | +}); |
| 67 | +``` |
0 commit comments