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.
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?