I have a class with a public method. It has other methods that \'assist\' with t
ID: 645966 • Letter: I
Question
I have a class with a public method. It has other methods that 'assist' with the purpose of the public method. The public method must be tested. However, I also want to unit test the private methods.
It would be impossible for my unit tests to call private methods and test them in isolation, so they must be public.
The problem here is that I'm left with code that, I feel, has been written with a lack of respect for OOP convention, purely for the sake of being able to unit test it.
Am I right in amending the access of methods purely for 'testability'? Or should I be rethinking and refactoring the structure as a whole to separate out the functionality of the private methods (despite the fact they don't do a lot at all and may, at times, resemble small helper methods)?
Explanation / Answer
Yes it is very bad practice - you're letting your tools make design decisions for you.
I think the main problem here is that you're trying to treat each individual method as a unit. This is generally the cause of all unit test woes. Except for some cases where your method is very complex and requires a lot of testing, you should be treating your classes as units. Martin Fowler even treats related classes as a unit too (sometimes).
As a result, you should be instantiating a class, then calling method(s) on its public interface as it would be used. This gives you your examples for your documentation, and ensures it works as the whole thing is intended. You should be trying here to test the private methods by calling the public ones - and if a private method is never called, then why do you still have it in code?
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.