I am wondering if unit testing private methods is a good practice?
Normally only public interface should be tested.
However, I have found out that during complex calculation, which calls tons of different private methods, it is easier to unit test the private methods first, and then make a simple test for the public interface method.
As an example let's say you have an audio player and you have functions:
void play(){ ... }
void pause(){ ... }
void seek(time t)
{
//All Private methods
checkIfValidTimeRange(...);
moveToFilePos(...);
fillBuffers(...);
}
Normally I would write unit tests for : checkIfValidTimeRange(...)
, moveToFilePos(...)
, fillBuffers(...)
.
But I am not sure if doing so is good practice.
To test private methods, you just need to test the public methods that call them. Call your public method and make assertions about the result or the state of the object. If the tests pass, you know your private methods are working correctly.
So whether you are using JUnit or SuiteRunner, you have the same four basic approaches to testing private methods: Don't test private methods. Give the methods package access. Use a nested test class.
It's not a good practice (yet that doesn't mean you should never do that), and if possible you want to avoid it. Testing private method usually means your design could be better. Let's take a quick look at your player example:
moveToFilePos
: sounds more like a responsibility of something doing I\O operations, not a music player'sfillBuffers
: more of a memory manager's job rather than music playercheckIfValidTimeRange
: again, probably could be moved out of player's scope to some simple validation class (seems like this one might be useful in other places aswell)At the moment your music player does I/O, memory management and what not else. Is that all really in scope of its responsibilities?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With