Open rbth7e5 opened 5 years ago
JUnit does not give you a nice way to test private methods. You can use a nested test class or use reflection. Reflection basically uses the method names as strings and is a kind of loophole to allow access to private methods. http://saturnboy.com/2010/11/testing-private-methods-in-java/ says that "the only real one is #4, use reflection"- indicating reflection as the only real way to test private methods.
However, https://dzone.com/articles/unit-testing-private-methods says that "In my mind, this is the worst of the suggested ways." when referring to reflection.
Some other people would argue that we should only test public methods- the private ones that get called along the way are also tested. However, I disagree with this as it is like saying that we don't need unit tests and can just do system tests- the units are tested along the way.
To answer your question, I would say "no"- there is no elegant way (at least I don't know of one).
Hi @rbth7e5,
@lingyanhao is right.
It is acceptable to test only public methods in the context of CS2103. However, unit testing for production code should include testing private methods as well. Reflection is a good way to test them (but not covered in CS2103). Another good alternative, many times used and preferred, is to make these private methods protected (package access).
As a rules of thumb, you should never make your private methods public to enable unit testing.
Best regards, Cristina.
Is there an elegant way to test private methods without making them public or moving them out?