Ravikumar
Ravikumar

Reputation: 211

How to write a test case for abstract class method

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.

Upvotes: 0

Views: 168

Answers (1)

Dave
Dave

Reputation: 3017

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
}

Upvotes: 3

Related Questions