Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Phpunit Exception assertion. For easy multiple testing if Exception is thrown in one test method. For PHP >= 5.5 you can use package with trait:
abstract class TestCase extends \PHPUnit_Framework_TestCase
protected function assertException(callable $callback, $expectedException = 'Exception', $expectedCode = null, $expectedMessage = null)
$expectedException = ltrim((string) $expectedException, '\\');
if (!class_exists($expectedException) && !interface_exists($expectedException)) {
$this->fail(sprintf('An exception of type "%s" does not exist.', $expectedException));
try {
} catch (\Exception $e) {
$class = get_class($e);
$message = $e->getMessage();
$code = $e->getCode();
$errorMessage = 'Failed asserting the class of exception';
if ($message && $code) {
$errorMessage .= sprintf(' (message was %s, code was %d)', $message, $code);
} elseif ($code) {
$errorMessage .= sprintf(' (code was %d)', $code);
$errorMessage .= '.';
$this->assertInstanceOf($expectedException, $e, $errorMessage);
if ($expectedCode !== null) {
$this->assertEquals($expectedCode, $code, sprintf('Failed asserting code of thrown %s.', $class));
if ($expectedMessage !== null) {
$this->assertContains($expectedMessage, $message, sprintf('Failed asserting the message of thrown %s.', $class));
$errorMessage = 'Failed asserting that exception';
if (strtolower($expectedException) !== 'exception') {
$errorMessage .= sprintf(' of type %s', $expectedException);
$errorMessage .= ' was thrown.';
Copy link

76200 commented Mar 24, 2016

@VladaHejda, great stuff, thanks! I think this should be a part of PHPUnit library by default.

Copy link

sweiguny commented May 14, 2018

is there an opposite function of $this->fail()? Like $this->succeed()?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment