00001 <?php 00002 // $Id: exceptions.php,v 1.1 2008/04/20 18:34:43 dries Exp $ 00003 00004 class SimpleExceptionTrappingInvoker extends SimpleInvokerDecorator { 00005 00010 function SimpleExceptionTrappingInvoker($invoker) { 00011 $this->SimpleInvokerDecorator($invoker); 00012 } 00013 00020 function invoke($method) { 00021 $trap = SimpleTest::getContext()->get('SimpleExceptionTrap'); 00022 $trap->clear(); 00023 try { 00024 parent::invoke($method); 00025 } 00026 catch (Exception $exception) { 00027 if (!$trap->isExpected($this->getTestCase(), $exception)) { 00028 $this->getTestCase()->exception($exception); 00029 } 00030 $trap->clear(); 00031 $this->_invoker->getTestCase()->tearDown(); 00032 } 00033 if ($message = $trap->getOutstanding()) { 00034 $this->getTestCase()->fail($message); 00035 } 00036 } 00037 } 00038 00047 class ExceptionExpectation extends SimpleExpectation { 00048 private$expected; 00049 00062 function __construct($expected, $message = '%s') { 00063 $this->expected = $expected; 00064 parent::__construct($message); 00065 } 00066 00072 function test($compare) { 00073 if (is_string($this->expected)) { 00074 return ($compare instanceof $this->expected); 00075 } 00076 if (get_class($compare) != get_class($this->expected)) { 00077 return false; 00078 } 00079 return $compare->getMessage() == $this->expected->getMessage(); 00080 } 00081 00087 function testMessage($compare) { 00088 if (is_string($this->expected)) { 00089 return "Exception [". $this->describeException($compare) ."] should be type [". $this->expected ."]"; 00090 } 00091 return "Exception [". $this->describeException($compare) ."] should match [". $this->describeException($this->expected) ."]"; 00092 } 00093 00099 protected function describeException($exception) { 00100 return get_class($exception) .": ". $exception->getMessage(); 00101 } 00102 } 00103 00111 class SimpleExceptionTrap { 00112 private$expected; 00113 private$message; 00114 00118 function __construct() { 00119 $this->clear(); 00120 } 00121 00130 function expectException($expected = false, $message = '%s') { 00131 if ($expected === false) { 00132 $expected = new AnythingExpectation(); 00133 } 00134 if (!SimpleExpectation::isExpectation($expected)) { 00135 $expected = new ExceptionExpectation($expected); 00136 } 00137 $this->expected = $expected; 00138 $this->message = $message; 00139 } 00140 00149 function isExpected($test, $exception) { 00150 if ($this->expected) { 00151 return $test->assert($this->expected, $exception, $this->message); 00152 } 00153 return false; 00154 } 00155 00160 function getOutstanding() { 00161 return sprintf($this->message, 'Failed to trap exception'); 00162 } 00163 00167 function clear() { 00168 $this->expected = false; 00169 $this->message = false; 00170 } 00171 }
1.5.5