Unit testing my private methods in PHP?

Ogheneruno Omene
2 min readJun 14, 2022

--

Well, there is no right or wrong answer to this question. Object Oriented Programming was created around method and property accessibly.

Usually, When deciding to create a method or a property, it always makes sense to ask questions like:

a. Do I them only in this class? Private

b. Do I need this class and in child classes? Protected

c. Do I need them in other classes unrelated to child classes? Public

This makes sense, although, protected and private methods could contain units/code blocks that you would love to test. I have had a conversation with a number of Engineers that believe that since it is a private method, means it should be tested via the public method that exposes it.

Take a look at the example below of a method in a class that attempts to fetch stripe keys from AWS secrets service and caches them so the application can use it;

Writing a test for this public method requires some sort of integration test and decisions have to be made to either call the service during the test (slows down your test significantly) or mock a response from the provider in this case AWS Secrets service.

Another option would be to test just the cache method and since it is private, making it public is usually my option. Knowing that this method’s scope is just within this class though, makes me cringe. Lol

Does my argument for testing a private method appeal to you yet? if it does, what if we can test this private method?

I know what you are thinking right now, we would use the PHP native class “setAccessible” method to make it public. Guess what? Thanks to the Spatie team, it is as little as calling a method on your class. Spatie invade does just that and it provides you with synthetic sugar to perform that action. Thus I can rewrite my tests as such

What do you guys think? Another awesome library from the Spatie team.

--

--