Skip to content

Commit

Permalink
make testing of inaccessible methods easier
Browse files Browse the repository at this point in the history
While it's generally frowned upon testing privates, it can often be
useful and the easier way to write tests. Eg you want to test something
complicated method that is important, but you do not want to expose it
directly to other classes...

This new method uses reflection to make access to such methods possible
from within tests without the need for intermediate classes.
  • Loading branch information
splitbrain committed Apr 13, 2018
1 parent 43d3f07 commit 210ff13
Showing 1 changed file with 20 additions and 0 deletions.
20 changes: 20 additions & 0 deletions _test/core/DokuWikiTest.php
Expand Up @@ -171,4 +171,24 @@ protected function waitForTick($init = false) {
$last = $now;
return $now;
}

/**
* Allow for testing inaccessible methods (private or protected)
*
* This makes it easier to test protected methods without needing to create intermediate
* classes inheriting and changing the access.
*
* @link https://stackoverflow.com/a/8702347/172068
* @param object $obj Object in which to call the method
* @param string $func The method to call
* @param array $args The arguments to call the method with
* @return mixed
* @throws ReflectionException when the given obj/func does not exist
*/
protected static function callInaccessibleMethod($obj, $func, array $args) {
$class = new \ReflectionClass($obj);
$method = $class->getMethod($func);
$method->setAccessible(true);
return $method->invokeArgs($obj, $args);
}
}

0 comments on commit 210ff13

Please sign in to comment.