Skip to content

Instantly share code, notes, and snippets.

Embed
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: 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);
}
}
@m-bymike
Copy link

m-bymike commented Nov 17, 2015

what about the @ExpectedException php-doc annotation built-in in PHPUnit?

@Begalov
Copy link

Begalov commented Jan 12, 2016

@ExpectedException skip any assertions after excepted (Codeception 2.0.16, PHPUnit 4.7.7)

@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

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