Contents
Why you should not test private methods?
The short answer is that you shouldn’t test private methods directly, but only their effects on the public methods that call them. The test should only be accessing the class’ public interface. If an object is hard to test via its public interface, it is going to be hard to use in the production code.
How do I test private methods?
From this article: Testing Private Methods with JUnit and SuiteRunner (Bill Venners), you basically have 4 options:
- Don’t test private methods.
- Give the methods package access.
- Use a nested test class.
- Use reflection.
Do you test private methods in a unit test?
Yes, don’t Test private methods…. The idea of a unit test is to test the unit by its public ‘API’. If you are finding you need to test a lot of private behavior, most likely you have a new ‘class’ hiding within the class you are trying to test, extract it and test it by its public interface. One piece of advice / Thinking tool…..
Can you test a private method in MS?
Private methods are used to have the abstraction in classes and some times created for code resuability purposes. If you are writing MS Tests for unit testing, then Microsoft provides a Private Object class through which you can test the private methods. But, I don’t think this is a good idea.
Is it better to test public or private methods?
You can get a false sense of security by seeing the green light on all the passing tests for your private methods. It is much better/safer to test edge cases on your private functions through your public interface.
How are private methods used in a class?
The idea of the original class is that its interface is the public methods. The package private methods are only helper methods, and not meant to be used from outside the class. For classes in the same package, we already rely on them to use it correctly (it can’t be enforced anyway).