How to use reflection to test private and protected methods

Share on facebook
Share on twitter
Share on linkedin

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 new Reflection class from our class:

Get the private/protected method:

Make it accessible:

Create and instance from our class:

Call the method with arguments on the instance created above:

Properties

In similar way we can 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 behaviour.

Create new Reflection class from our class:

Get the private/protected property:

Make it accessible:

Create and instance from our class:

Set the value of the property on the created instance:

You can find more information about the reflection in the php documentation: https://www.php.net/manual/en/book.reflection.php

Subscribe to our newsletter

Be first to read new helpful post

Share this post with your friends

Share on linkedin
Share on xing
Share on twitter
Share on facebook

Communian – COMING SOON

We at 42coders love meetups and think that they are a valuable asset to the community. And we willingly attend to them. Not to mention

Leave a Reply

avatar
  Subscribe  
Notify of