Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Unit testing class with a private constructor?

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 ?

like image 238
Win Coder Avatar asked Mar 27 '13 16:03

Win Coder


3 Answers

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")]
like image 63
Jim Sowers Avatar answered Sep 19 '22 23:09

Jim Sowers


If this class has a private constructor, is this to be used publicly? If not, it may be best not to unit test it. If this is the case, the code that is public should test this code in itself by calling it.

Unit testing is there to test what is to be used by the public - by interfacing code in between application layers for instance. Take an input, I want this output. That is really what unit testing is about. Unit testing doesn't care what is in the actual method. As long as it returns what you want, performs the desired action, you have a pass.

like image 8
rhughes Avatar answered Sep 21 '22 23:09

rhughes


You should be testing through a public API -- there must be some way that the class you want to test is instantiated and used.

like image 2
Daniel Mann Avatar answered Sep 20 '22 23:09

Daniel Mann