I have a C# class of the following structure
public class ClassA{
protected ClassA(double[] number){
}
public double methodofClassA(){
}
}
I would like to invoke methodofClassA()
for unit testing that method. But, I am unable to do so due to protected constructor. In legacy code, they have used accessors. But as its deprecated in the latest versions of .NET framework, how to resolve this and test that method after removing accessors?
TIA
2
Answers
You can make the CTOR accessible to your test harness by inheritance:
See also this Fiddle
Since the protected CTOR is accessible to classes inheriting the class under test,
all you need to do is to derive from it and you should be able to perform all the tests through this indirection.
The other question would be: Do you actually need to? If you test the deriving classes, this base should already be covered plenty.
In general you should be testing the public API of the class. So you should be creating the class the same way any other users of the class does it. If the class is only intended as a base class, test the derived classes.
If the class is only intended to be part of something larger you might be testing the wrong "unit". The "unit" in unit testing can be of any size, it does not have to be a class. It could be some collection of classes that are internally tightly coupled, or an entire assembly if it has a simple enough public API, or a single method.
That said, in some cases you just need a pragmatic solution to a specific problem. In that case I would tend to just supply a clearly named public method.