Skip to content

Instantly share code, notes, and snippets.

@Finesse
Last active June 27, 2018 02:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Finesse/6e1ca58f2f20e8999358c9b359b0f5ae to your computer and use it in GitHub Desktop.
Save Finesse/6e1ca58f2f20e8999358c9b359b0f5ae to your computer and use it in GitHub Desktop.
PHPUnit assert exception method
<?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