Skip to content

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
3 public void PublicMethod();
4 protected void PrivateMethodToTest();
7public class TestClass : Class
9 public void PrivateMethodToTestWrapper() => PrivateMethodToTest();

and use it in your tests as

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