Nunit - 测试受保护的方法默认构造函数缺少异常

Row*_*ish 1 c# inheritance nunit exception protected

我想(使用NUnit)测试以下类,特别是protected方法ProtectedMethod

public class Foo
{
    protected bool ProtectedMethod()
    {
        //...
    }
}
Run Code Online (Sandbox Code Playgroud)

为了访问受保护的方法,我编写了一个Foo以这种方式继承的测试类:

[TestFixture]
internal class FooTestable : Foo
{
    [Test]
    public void ProtectedMethod_Test()
    {
        bool result = ProtectedMethod();
        Assert.That(result);
    }
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误:

FooTestable does not have a default constructor
Run Code Online (Sandbox Code Playgroud)

这是什么意思?

这是测试受保护方法的最佳方法吗?

Val*_*tin 5

我认为测试受保护方法的最佳方法是创建继承基类FooTestable和 TestClass的类的可测试实现,FooTests并将这些类分开。

public class FooTestable : Foo
{
    public new bool ProtectedMethod()
    {
        return base.ProtectedMethod();
    }

    public FooTestable () {}
}

[TestFixture]
public class FooTests
{
    [Test]
    public void ProtectedMethod_Test()
    {
        FooTestable fooInstance = new FooTestable();

        Assert.That(fooInstance.ProtectedMethod());
    }
}
Run Code Online (Sandbox Code Playgroud)

FooTestable 没有默认构造函数

该错误意味着基类Fooa 具有带参数的构造函数并且没有默认构造函数,因此您需要向子类添加一个构造函数并使用base关键字从中调用基构造函数。

例如

    public FooTestable ():base(1,2,3)/*calling the base class constructor*/ {}
    public FooTestable (int a, int b, int c):base(a,b,c) {}
Run Code Online (Sandbox Code Playgroud)