PHPUnit Testing - Test Protected/Private Functions?

PHPUnit Testing - Test Protected/Private Functions?

by Benjamin Ellis -
Number of replies: 2
Picture of Particularly helpful Moodlers

"It's a bad sign, if you need to test protected methods. The aim of a unit test, is to test the interface of a class, and protected methods are implementation details."

Does anyone know if this is the 'official' Moodle HQ view on PHPUnit testing for core components?  What are your organisations and thoughts about this subject?

Average of ratings: -
In reply to Benjamin Ellis

Re: PHPUnit Testing - Test Protected/Private Functions?

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers
The thing about good design in software is that implementation details should be hidden. This is particularly true in Object oriented software, where each class should encapsulate a certain part of the problem and expose a nice interface to the outside world.

And, one of the reasons you do that, is so that, if it becomes necessary, you can change the private implemenation to somthing better without having to rewrite the whole system (or update a lot of automated tests which incorrectly depend on the current implementation).

The other way to look at this is, what the end user actually cares about is the externally visible functionality. So, the things you want to test are those user-visible requirements. (E.g. if the user submits this answer to this quiz question, they get this mark.) Almost alwasy it is possble to test this with public methods.

So, irrespective of how strict this Moodle rule is, it is just generally a good way to think about software / test design. So, I encorage you to try to work towards it, even if that seems hard now.

See also https://martinfowler.com/articles/practical-test-pyramid.html#private-methods-sidebar.
Average of ratings: Useful (1)