Skip to content

Instantly share code, notes, and snippets.

@VladaHejda
Last active December 28, 2022 03:59
Show Gist options
  • Star 19 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save VladaHejda/8826707 to your computer and use it in GitHub Desktop.
Save VladaHejda/8826707 to your computer and use it in GitHub Desktop.
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: https://packagist.org/packages/vladahejda/phpunit-assert-exception
<?php
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 {
$callback();
} 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));
}
return;
}
$errorMessage = 'Failed asserting that exception';
if (strtolower($expectedException) !== 'exception') {
$errorMessage .= sprintf(' of type %s', $expectedException);
}
$errorMessage .= ' was thrown.';
$this->fail($errorMessage);
}
}
@76200
Copy link

76200 commented Mar 24, 2016

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

@sweiguny
Copy link

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