Last active
October 22, 2019 13:51
-
-
Save bigonese/6497676 to your computer and use it in GitHub Desktop.
Example of how a "test mode" can be incorporated into a class (eg, a class that interacts with a database) so that it can be unit tested as much as possible.
This file contains 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 | |
// Used to make sure test mode isn't entered into on accident | |
class TestModeException extends Exception { } | |
// Used to return a testable value as far into the logic that the test can reach | |
class TestResultsException extends Exception { } | |
// The class which will be tested | |
class TestableClass { | |
private $testMode = false; | |
public function setTestMode() { | |
$this->testMode = true; | |
throw new TestModeException(__CLASS__.' entered test mode!'); | |
} | |
public function itsComplicated() { | |
$sql = "UPDATE `Stuff`"; | |
if ($this->testMode) throw new TestResultsException($sql); | |
// else do the normal production logic | |
} | |
} | |
// The test | |
class TestableClassTest extends PHPUnit_Framework_TestCase { | |
public $testObj = | |
public function setup() { | |
$this->testObj = new TestableClass(); | |
try { | |
$this->testObj->setTestMode(); | |
} catch (TestModeException $e) { | |
// This is good! | |
} | |
// (Other exceptions not caught) | |
} | |
public function testItsComplicated() { | |
try { | |
$this->testObj->itsComplicated(); | |
} catch (TestResultsException $e) { | |
// This is expected! | |
$this->assertTrue($e->getMessage() == 'UPDATE `Stuff`'); | |
} | |
// (Other exceptions not caught) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I'm seeing ~3 concerns here:
I think the more you do TDD, the more testable your code will become, and the less you'll need the second one. But I think it's a good way to cover hard-to-test code without a rewrite. Clever! I'm going to have to steal that.