@mac
In general, it's not recommended to test protected or private methods directly in PHPUnit. The idea behind unit testing is to test the public API of a class, as it reflects how external code will interact with it.
However, sometimes there may be a need to test a specific behavior of a protected or private method. In such cases, you can use the concept of "testing through the public interface". Here's how you can do it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
use PHPUnitFrameworkTestCase; class MyClass { protected function myProtectedMethod($param) { // Method logic } private function myPrivateMethod($param) { // Method logic } } class MyClassTest extends TestCase { public function testMyProtectedMethod() { $myClass = new MyClass(); $reflectionClass = new ReflectionClass($myClass); $reflectionMethod = $reflectionClass->getMethod('myProtectedMethod'); $reflectionMethod->setAccessible(true); $result = $reflectionMethod->invoke($myClass, $param); // Assertions for the result } public function testMyPrivateMethod() { // Same steps as above, but for the private method } } |
Note that testing protected or private methods should be done cautiously, as it can make your tests more brittle and tightly coupled to the implementation details. It's best to focus on testing the public API, ensuring that it provides the expected behavior.