Last active
December 28, 2022 03:59
-
-
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
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 | |
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); | |
} | |
} |
@ExpectedException skip any assertions after excepted (Codeception 2.0.16, PHPUnit 4.7.7)
@VladaHejda, great stuff, thanks! I think this should be a part of PHPUnit library by default.
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
what about the @ExpectedException php-doc annotation built-in in PHPUnit?