Last active
December 29, 2015 17:09
-
-
Save ericmann/7702180 to your computer and use it in GitHub Desktop.
Quicky PHPUnit accessiblity example.
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 | |
/** | |
* This class contains two private methods we wish to test. | |
* In reality, it would also contain several public methods, | |
* but that's immaterial to our discussion. | |
* | |
* @package Tutorials | |
*/ | |
class ClassToTest { | |
/** | |
* Does something cool | |
* | |
* @returns string | |
*/ | |
private function someFunction() { | |
return 'expected'; | |
} | |
/** | |
* Filters an array | |
* | |
* @param array $array | |
* | |
* @returns array | |
*/ | |
private function someOtherFunction( $array ) { | |
return array_filter( $array, 'remove_even_elements' ); | |
} | |
} | |
/** | |
* The test class is using vanilla PHPUnit code and the standard | |
* PHP reflection API. | |
* | |
* @package Tutorials | |
* @subpackage Tests | |
*/ | |
class TestCase extends PHPUnit_Framework_TestCase { | |
public function test_someFunction() { | |
$instance = new ClassToTest(); | |
// Get a handle to the private method | |
$someFunction = new ReflectionMethod( | |
'ClassToTest', | |
'someFunction' | |
); | |
$someFunction->setAccessible( true ); | |
$result = $someFunction->invoke( $instance ); | |
$this->assertEquals( 'expected', $result ); | |
} | |
public function test_someOtherFunction() { | |
$instance = new ClassToTest(); | |
// Get a handle to the private method | |
$someFunction = new ReflectionMethod( | |
'ClassToTest', | |
'someOtherFunction' | |
); | |
$someOtherFunction->setAccessible( true ); | |
$initialArray = array( 1, 2, 3 ); | |
// Assume the filtering function removes any even members from the array. | |
$filteredArray = $someOtherFunction->invoke( $instance, $initialArray ); | |
$this->assertEquals( 2, count( $filteredArray ) ); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment