Testing

How to use reflection to test private and protected methods

Daniel Verner -

Developing application with TDD methodology we tend to achieve the highest possible code coverage, including private and protected methods as well. But writing unit test for a non-public method is not trivial. Changing the visibility for the sake of unit tests is not a good idea. In these cases, we can use PHP's reflection to make those methods accessible, letโ€™s see how.

Methods
Create a new Reflection class from our class:
$class = new \ReflectionClass('MyNamespace\MyClass');
Get the private/protected method:
 $myProtectedMethod = $class->getMethod('myProtectedMethod');
Make it accessible:
$myProtectedMethod->setAccessible(true);
Create an instance from our class:
$myInstance = new MyClass();
Call the method with arguments on the instance created above:
$result = $myProtectedMethod->invokeArgs($myInstance, [$argument1, $argument2]);

Properties
In a similar way, we can change the visibility of the non-public properties of a class. This could be useful when we want to unit test edge cases or error handling, and we want to change the internal state of the instance to simulate the erroneous behavior.

Create a new Reflection class from our class:
$class = new \ReflectionClass('MyNamespace\MyClass');
Get the private/protected property:
$myProtectedProperty = $class->getProperty(myProtectedProperty);
Make it accessible:
$myProtectedProperty->setAccessible(true);
Create an instance from our class:
$myInstance = new MyClass();
Set the value of the property on the created instance:
$myProtectedProperty->setValue($myInstance, 'value');
You can find more information about the reflection in the PHP documentation: https://www.php.net/manual/en/book.reflection.php

Tags: testing · PHP · phpUnit · reflection

Want products news and updates?

Sign up for our newsletter to stay up to date.

We care about the protection of your data. Read our Privacy Policy.

Impressions from our Team

  • Happy birthday ๐ŸŽ๐ŸŽˆ๐ŸŽ‚ Filip - #

  • Another day another #mandarinacakeshop ๐ŸŽ‚ ๐Ÿ˜€ - #

  • Happy Birthday Ognjen! And marry Christmas to all other ๐ŸŽ„#notacakeshop - #

  • #Office #Garden - #

  • #workhard - #

  • #belgrade #skyline - #

  • #happybirthday Phil :) - #

  • #happybirthday Stefan ๐Ÿฅ‚ - #

  • #happybirthday Lidija ๐Ÿพ - #

  • Say hi ๐Ÿ‘‹ to our newest team member โ˜•๏ธ - #

  • #bithday #cake ๐Ÿ˜ป - #

  • #stayathome #homeoffice #42coders - #

  • #stayathome #homeoffice #42coders #starwars :) - #

  • #stayathome #homeoffice #42coders - #

  • We had a really nice time with #laracononline #laravel - #

  • Happy Birthday ๐ŸŽ‚ Miloลก - #

  • Happy Birthday ๐ŸŽ‚Nikola - #

  • #42coders #christmas #dinner what a nice evening :) - #

  • Happy Birthday ๐ŸŽ‚ Ognjen - #

  • Wish you all a merry Christmas ๐ŸŽ„๐ŸŽ - #

See more!

© 2024 42coders All rights reserved.