note 110356 added to language.exceptions.extending

From: Date: Mon, 15 Oct 2012 04:56:00 +0000
Subject: note 110356 added to language.exceptions.extending
Groups: php.notes 
Request: Send a blank email to php-notes+get-191295@lists.php.net to get a copy of this message
Custom exception classes can allow you to write tests that prove your exceptions are meaningful. Usually testing exceptions, you either assert the message equals something in which case you can't change the message format without refactoring, or not make any assertions at all in which case you can get misleading messages later down the line. Especially if your $e->getMessage is something complicated like a var_dump'ed context array. The solution is to abstract the error information from the Exception class into properties that can be tested everywhere except the one test for your formatting. <?php class TestableException extends Exception { private $property; function __construct($property) { $this->property = $property; parent::__construct($this->format($property)); } function format($property) { return "I have formatted: " . $property . "!!"; } function getProperty() { return $this->property; } } function testSomethingThrowsTestableException() { try { throw new TestableException('Property'); } Catch (TestableException $e) { $this->assertEquals('Property', $e->getProperty()); } } function testExceptionFormattingOnlyOnce() { $e = new TestableException; $this->assertEquals('I have formatted: properly for the only required test!!', $e->format('properly for the only required test') ); } ?> ---- Server IP: 69.147.83.199 Probable Submitter: 70.96.69.178 ---- Manual Page -- http://www.php.net/manual/en/language.exceptions.extending.php Edit -- https://master.php.net/note/edit/110356 Del: integrated -- https://master.php.net/note/delete/110356/integrated Del: useless -- https://master.php.net/note/delete/110356/useless Del: bad code -- https://master.php.net/note/delete/110356/bad+code Del: spam -- https://master.php.net/note/delete/110356/spam Del: non-english -- https://master.php.net/note/delete/110356/non-english Del: in docs -- https://master.php.net/note/delete/110356/in+docs Del: other reasons-- https://master.php.net/note/delete/110356 Reject -- https://master.php.net/note/reject/110356 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#191295) next »