Testing Private Methods in Static Classes: The Not-So-Easy Way


I had a problem with testing a method: The method is intentionally private, as exposing it public wouldn’t benefit anyone and it merely reduces code-overhead for repeated operations – given ‘x’ condition.

In this case, it was if the product of two numbers was greater than nine, then take those numbers and add them together and that was the new number. So, for example, if the product was ten, we would then add one and zero and get the new number 1; or if it was eleven, we would get one and one, which is two, and so on…

So, because the class is static and can be instantiated without a reference, you can’t reference it as a PrivateType, which I came to quickly realize:

PrivateTestFailure

The way to get around this, was to construct the type, itself (since it’s static), and try to access the private method from that instantiation:

PrivateTestSucceeding

Once that happens, your tests should now be able to access your private static method contained within your public static class.


Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.