简体   繁体   English

如何为抽象类方法编写测试用例

[英]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. 这是我的代码,我想为Build方法编写一个单元测试,作为为类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. 在调用构建方法时,我的代码由于未传递IB实例而引发异常。 I not sure how to pass a mock object of IB to abstract class A through child class D. 我不确定如何通过子类D将IB的模拟对象传递给抽象类A。

This is because Constructors are not inherited in C#. 这是因为构造函数未在C#中继承。

Your base class, A has a constructor that takes an instance of IB and intialises the field. 您的基类A具有一个构造函数,该构造函数接受IB的一个实例并初始化该字段。 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 您需要为D提供一个接受IB实例的构造函数,然后将其传递给像这样的基本构造函数

public D(IB instanceOfIB)
    : base(instanceofIB)
{
    //do other things here if you want or leave empty
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM