Skip to content

Instantly share code, notes, and snippets.

@bigonese
Last active October 22, 2019 13:51
Show Gist options
  • Save bigonese/6497676 to your computer and use it in GitHub Desktop.
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.
<?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)
}
}
@bradobro
Copy link

bradobro commented Sep 9, 2013

I'm seeing ~3 concerns here:

  1. Using TestModeException to prevent inadvertent test mode in production environment. I like this a lot.
  2. Using TestResultsException to extract unit-level tests results from a class with high coupling before it hits other parts of the system.
  3. Guess I only see two ;).

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment