你如何对接口进行单元测试?

Che*_*tan 24 tdd unit-testing interface

例如,有一个接口IMyInterface,有三个类支持这个接口:

class A : IMyInterface
{
}

class B : IMyInterface
{
}

class C : IMyInterface
{
}
Run Code Online (Sandbox Code Playgroud)

用最简单的方法,我可以编写三个测试类:ATest,BTest,CTest并分别测试它们.但是,由于它们支持相同的接口,因此大多数测试代码都是相同的,很难维护.如何使用简单易用的方法测试不同类支持的接口?

(之前在MSDN论坛上询问过)

Tim*_*oyd 41

如果要使用NUnit作为示例对接口的不同实现者运行相同的测试:

public interface IMyInterface {}
class A : IMyInterface { }
class B : IMyInterface { }
class C : IMyInterface { }

public abstract class BaseTest
{
    protected abstract IMyInterface CreateInstance();

    [Test]
    public void Test1()
    {
        IMyInterface instance = CreateInstance();
        //Do some testing on the instance...
    }

    //And some more tests.
}

[TestFixture]
public class ClassATests : BaseTest
{
    protected override IMyInterface CreateInstance()
    {
        return new A();
    }

    [Test]
    public void TestCaseJustForA()
    {
        IMyInterface instance = CreateInstance();   
        //Do some testing on the instance...
    }

}

[TestFixture]
public class ClassBTests : BaseTest
{
    protected override IMyInterface CreateInstance()
    {
        return new B();
    }
}

[TestFixture]
public class ClassCTests : BaseTest
{
    protected override IMyInterface CreateInstance()
    {
        return new C();
    }
}
Run Code Online (Sandbox Code Playgroud)

  • +1 很好的答案!如今,NUnit 支持通用测试类,并且 TestFixture 属性可用于提供测试运行时要使用的特定类型。我写了一篇关于如何测试的[博客文章](http://softwareonastring.com/2015/03/22/testing-every-implementer-of-an-interface-with-the-same-tests-using-nunit)展示这些功能的界面的每个实现者。 (3认同)

mdm*_*dma 20

要测试具有常见测试的接口而不管实现如何,您可以使用抽象测试用例,然后为接口的每个实现创建测试用例的具体实例.

抽象(基础)测试用例执行实现中立测试(即验证接口契约),而具体测试负责实例化要测试的对象,并执行任何特定于实现的测试.