Monday 16 July 2018

Unit Testing Private Methods and Properties with PHPUnit




Let’s say we have a class Foo with private method bar and property foobar:

To call a private/protected method in a test, simply use reflection to set the accessibility of the method to public:
The first argument of invokeArgs() is an instance of the object, the second argument is an array of parameters to pass to the method.
We can make this a little more abstract for re-use elsewhere in our test class:

To access the value to a private/protected property, you can use reflection to set the accessibility in a similar fashion:

Reflection really opens up unit testing to those class internals without making them public so that every unit can be independently tested to find where code ‘breaks down’ as the application evolves.

For private/protected properties you can alsou use PHPUnit_Framework_Assert::readAttribute($classInstance, "propertyName")

0 comments:

Post a Comment