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.