Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 456
Anton Avatar asked Feb 08 '12 22:02

Anton


People also ask

Can you test private methods?

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.

Can we write JUnit for private methods?

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.


1 Answers

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

like image 160
k.m Avatar answered Sep 28 '22 04:09

k.m