Last active
June 27, 2018 02:23
-
-
Save Finesse/6e1ca58f2f20e8999358c9b359b0f5ae to your computer and use it in GitHub Desktop.
PHPUnit assert exception method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Add this method to your test class | |
/** | |
* Asserts that the given callback throws the given exception. | |
* | |
* @param string $expectClass The name of the expected exception class | |
* @param callable $callback A callback which should throw the exception | |
* @param callable|null $onException A function to call after exception check. It may be used to test the exception. | |
*/ | |
protected function assertException(string $expectClass, callable $callback, callable $onException = null) | |
{ | |
try { | |
$callback(); | |
} catch (\Throwable $exception) { | |
$this->assertInstanceOf($expectClass, $exception, "The thrown exception is not an instance of $expectClass"); | |
if ($onException) { | |
$onException($exception); | |
} | |
return; | |
} | |
$this->fail('No exception has been thrown'); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment