Skip to content

Instantly share code, notes, and snippets.

@ktomk
Created March 20, 2016 12:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ktomk/c9b5f5dd0333a6edc47a to your computer and use it in GitHub Desktop.
Save ktomk/c9b5f5dd0333a6edc47a to your computer and use it in GitHub Desktop.
PHPUnit_ExceptionTrap
<?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