skip to Main Content

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


  1. You can make the CTOR accessible to your test harness by inheritance:

    using System;
                        
    public class Program
    {
        public static void Main()
        {
            Console.WriteLine(new TestShim(3.5).ClassAMethod());
        }
    }
    
    public class ClassA
    {
        private readonly double _value;
        
        protected ClassA( double @value )
        {
            _value = @value;
        }
        
        public double ClassAMethod() { return _value; }
    }
    
    public class TestShim : ClassA
    {
        public TestShim( double a ) : base(a) {}
    }
    

    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.

    Login or Signup to reply.
  2. 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.

    public class ClassA{
        public static ClassA CreateInstanceForTestingOnly(double[] number) => new (number); 
        protected ClassA(double[] number){
        }
        public double methodofClassA(){
        }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search