Is there a way to unit-test protected or private methods of a class? As it is now, I'm making a lot of methods public in order to be able to test them, which breaks the API.
Edit: Actually answered here: Best practices to test protected methods with PHPUnit
You can access your private and/or protected method by using the ReflectionMethod class followed by invoke method, but to invoke the method you also need an instance of your class which in certain situations isn't possible. Based on this one nice example that works is this one:
Get a mock of your class:
$mockedInstance = $this->getMockBuilder(YourClass::class)
->disableOriginalConstructor() // you may need the constructor on integration tests only
->getMock();
Get your method to be tested:
$reflectedMethod = new \ReflectionMethod(
YourClass::class,
'yourMethod'
);
$reflectedMethod->setAccessible(true);
Call your private/protected method:
$reflectedMethod->invokeArgs( //use invoke method if you don't have parameters on your method
$mockedInstance,
[$param1, ..., $paramN]
);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With