Created
March 20, 2016 12:00
-
-
Save ktomk/c9b5f5dd0333a6edc47a to your computer and use it in GitHub Desktop.
PHPUnit_ExceptionTrap
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 | |
class PHPUnit_ExceptionTrap | |
{ | |
/** | |
* @var PHPUnit_Framework_TestCase | |
*/ | |
private $testCase; | |
/** | |
* @var Exception | |
*/ | |
private $trapped; | |
/** | |
* ExceptionTrap constructor. | |
* | |
* @param PHPUnit_Framework_TestCase $testCase | |
*/ | |
public function __construct(PHPUnit_Framework_TestCase $testCase) | |
{ | |
$this->testCase = $testCase; | |
} | |
/** | |
* @param callable $callable | |
* @param string|object $expected [optional] | |
* @return $this | |
*/ | |
public function trap(callable $callable, $expected = null) | |
{ | |
$this->trapped = null; | |
try { | |
call_user_func($callable); | |
} catch (Exception $e) { | |
$this->trapped = $e; | |
if ($expected !== null) { | |
$className = is_string($expected) ? $expected : get_class($expected); | |
$this->testCase->assertInstanceOf($className, $e); | |
} | |
} | |
return $this; | |
} | |
/** | |
* @param $expectedException | |
* @return $this | |
*/ | |
public function exception($expectedException) | |
{ | |
$this->testCase->assertInstanceOf(Exception::class, $this->trapped); | |
/* @see PHPUnit_Framework_TestCase::runTest */ | |
$this->testCase->assertThat( | |
$this->trapped, | |
new PHPUnit_Framework_Constraint_Exception( | |
$expectedException | |
) | |
); | |
return $this; | |
} | |
/** | |
* @param $expectedExceptionMessage | |
* @return $this | |
*/ | |
public function message($expectedExceptionMessage) | |
{ | |
$this->testCase->assertInstanceOf(Exception::class, $this->trapped); | |
/* @see PHPUnit_Framework_TestCase::runTest */ | |
$this->testCase->assertThat( | |
$this->trapped, | |
new PHPUnit_Framework_Constraint_ExceptionMessage( | |
$expectedExceptionMessage | |
) | |
); | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment