C# Unit testing class with a private constructor

cnetnunitunit testing

Ok so i just got an assignment where i have to perform unit testing on a class with a private constructor.

Now how am i suppose to do unit testing without initializing a class when all the methods are also non static.

Is there any way i can do unit testing(without reflection)on a class with a private constructor ?

Best Answer

If you cannot make the class public, you can still test it easily by creating an instance of it this way:

var anInstance = (YourPrivateClass)Activator.CreateInstance(typeof(YourPrivateClass), true);

This will give you an instance of your class that you can then populate.

Another helpful testing bit is if you have internal methods (not private), you can access them by making internals visible to your test class. You add this line in assemblyinfo.cs of the class with the internal methods:

[assembly: InternalsVisibleTo("YourSolution.Tests")]