userone
userone

Reputation: 321

Unit test a method/class that has numerous private methods

I'm writing unit tests and noticed that one of my class is basically one public method that in turn calls several private methods (and some protected methods from base class).

Would the "recommended" method be to test the one public method several times to cover the private/protected methods? Or do some refactoring (like make a public method that can be called by unit test that in turn makes a call to private method like so:

public void Main()
{
   PublicMethod1();
   PublicMethod2();
}

public void PublicMethod1()
{
   PrivateMethod1();
}

public void PublicMethod2()
{
   PrivateMethod2();
}

private void PrivateMethod1()
{
}
private void PrivateMethod2()
{
}

Upvotes: 0

Views: 46

Answers (1)

David
David

Reputation: 219016

Would the "recommended" method be to test the one public method several times to cover the private/protected methods?

That's generally what I'd recommend. If you have to re-factor the class just to test it then that implies an incorrect design in the first place. Alternatively, if there exists private functionality which can't be reached/covered by testing the public functionality then an argument can be made to just remove that unreachable code entirely.

Tests are "consuming code" just like any other "consuming code". And private/encapsulated functionality should be a "black box" to consuming code. Any refactoring which doesn't change the public-facing functionality should have no effect on the tests. If it does, the tests are too tightly coupled with the internal implementation details.

Test the public interface exposed by the class. After all, that's the functionality being used, so that's the functionality that should be tested.

Upvotes: 0

Related Questions