0

Here is my code, I want to write a unit test for Build method as part of writing a test case for class D.

public class X
{

}

public interface IB
{
    X GetX(X value);
}

public class B : IB
{
    public X GetX(X value)
    {
        //ToDo:
    }
}

public abstract class A
{
    private IB obj;
    public A(IB obj)
    {
        this.obj = obj;
    }
    public X Build()
    {
        return obj.GetX();
    }
}

public class D : A
{
    public void display()
    {
        //TODO
    }
}

//Test Method

[Test]

public void Test_Build(){
var mock = new Mock<IB>();

var objA = new D();
objA.Build();

}

here is my test method. While calling build method my code is throwing an exception because of not passing the instance of IB. I not sure how to pass a mock object of IB to abstract class A through child class D.

Ravikumar
  • 211
  • 1
  • 10

1 Answers1

3

This is because Constructors are not inherited in C#.

Your base class, A has a constructor that takes an instance of IB and intialises the field. However your inheriting class has no constructor specified and so has a Default parameterless constructor.

You need to provide a constructor for D that takes an instance of IB and then pass this upto the base constructor like this

public D(IB instanceOfIB)
    : base(instanceofIB)
{
    //do other things here if you want or leave empty
}
Dave
  • 2,829
  • 3
  • 17
  • 44
  • @Ravikumar Here is a good article by Jon Skeet on Constructors. They are not as simple as they seem. http://jonskeet.uk/csharp/constructors.html – Dave Oct 17 '18 at 13:55