Skip to content
ashique

unit testing private methods

testing1 min read

when we find ourselves wanting to test our private methods, it's usually because exercising the public api does not provide enough coverage of the individual private units, which are of sufficient complexity that warrants rigorous testing.

in some scenarios, it might be a good idea to refactor out the private methods in their own classes, expose public apis and consume them and, test those public apis. however, there are situations when breaking them apart into separate classes obscures the logical flow of the program overall and, yet they warrant the first-class treatment when it comes to testing.

in such situations, i have found that it's often worth giving up a little bit of privacy for testing. almost all OOP languages allow you to loosen up the privacy to a reasonable extent, such as making it accessible to the same package internally.

testing > privacy

here's an example:

1public class Class
2{
3 public void PublicMethod();
4 protected void PrivateMethodToTest();
5}
6
7public class TestClass : Class
8{
9 public void PrivateMethodToTestWrapper() => PrivateMethodToTest();
10}

and use it in your tests as

1public void UnitTest()
2{
3 var sut = new TestClass();
4 sut.PrivateMethodToTestWrapper();
5}
© 2022 by ashique mahmood. all rights reserved.