Writing tests can be repetitive, even if you try to adhere to DRY principals. I’m using the PHP Simple Test library to run my tests, since it’s been written, it’s good and there’s no reason for me to write my own. However, I’m not using a heavy framework with an ORM, rather a light framework (Swiftlet) with my own DAO.
Here are my test utilities so far, they’ve been useful for general models and have helped increase test coverage while reducing code:
<?php /** * TestUtils * Utilities not included in test library that are commonly used in tests * * copyright 2010 logon2 http://www.logon2.com.au * license http://opensource.org/licenses/gpl-3.0.html GNU Public License */ class TestUtils { function confirmSaveAndRestore($saved, $restored) { /* * Confirms the values saved to a database are * retreived accurately. * saved can either be an array of key/value pairs OR * an array of an array of key/value pairs. * * The format of $restored must match that of $saved */ //determine if we're testing multiple values if (is_array($saved)) { foreach ($saved as $key => $value) { if (!$key) { $array = true; } else { $array = false; break; } } } else { //the input MUST be an array or an array of an array throw new Exception("Input must be at least a 1D array"); } if ($array = false) { $responses = array($saved); } else { $responses = $saved; } foreach ($responses as $response) { if (is_array($saved) && is_array($restored)) { foreach ($saved as $key => $value) { if ($restored[$key] != $value) { return false; } } return true; } else { throw new Exception("Inconsistent input"); } } } function overwriteAttributes($attributes, $updates) { /* * Will overwrite attributes from $attributes with all attributes * found in $updates, but leave all others * * This can be useful for testing edits */ if (is_array($updates)) { foreach ($updates as $key => $value) { $attributes[$key] = $value; } } return $attributes; } function generateBadValSet($badVals, $goodVals) { /* * Will generate a complete set of values, * each with exactly one bad value from $badVals * * I was thinking if I should make it generate * all possibilities (n^m) rather than just * a set of values each with exactly one bad value. */ $badValSet = array(); foreach($badVals as $attribute => $badVal) { if (!is_array($badVal)) { //more than one bad value for attribute $badVal = array($badVal); } foreach ($badVal as $thisBadVal) { $theseBadVals = $goodVals; $theseBadVals[$attribute] = $thisBadVal; $badValSet[] = $theseBadVals; } } return $badValSet; } } ?>
Ironically, I have no test for these Test Utilities so beware