Search code examples
phpunit-testingencapsulation

Unit testing and encapsulation


I'm trying to get into unit testing, but there's one thing bothering me.

I have a php class which I want to unit test. It takes some parameters, and then spits out HTML. The problem is that the main functionality is calculating some values and conditions, and these I want to test. But I have put this in a private method, because normally, nobody needs to know about this method. But this way I am not possible to unit test the class because I have no means of testing the result of the method.

I have found this article about the subject. The conclusion of the article is using reflection to test the private methods.

How do you stand against this subject?


Solution

  • You should have the logic in its own class and then unit test that class, so you don't have to reach through the html in order to test the logic.

    As a rule:

    You should never test private methods. The private methods exists in order to make the public methods pass their tests.

    If you can delete the private methods without breaking the public methods, you don't need the private methods and can delete them.

    If you can't delete the private methods without breaking the public methods, then the private methods are being tested.

    If you follow the practice of TDD, it would be hard to get into this situation because every line of code is written to make unit tests pass. There should be no "stray" code within your class.