Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

c++ - Is unit testing private methods a good practice?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 IO operations, not a music player's
  • fillBuffers: more of a memory manager's job rather than music player
  • checkIfValidTimeRange: 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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...