重用多个实现的测试套件?

Chr*_*ris 5 nunit unit-testing

我正在使用nUnit进行测试.我有一套针对我的IFoo接口运行的测试; 测试夹具设置确定要加载和测试的IFoo实现.

我试图弄清楚如何针对IFoo实现列表运行相同的套件,但是没有任何方法来测试所有实现而无需手动修改安装程序.

有人解决了这个问题吗?

Wim*_*nen 12

创建一个基本测试类,其中包含在IFoo实现之间共享的测试,如下所示:

// note the absence of the TestFixture attribute
public abstract class TestIFooBase
{
   protected IFoo Foo { get; set; }

   [SetUp]
   public abstract void SetUp();

   // all shared tests below    

   [Test]
   public void ItWorks()
   {
      Assert.IsTrue(Foo.ItWorks());
   }
}
Run Code Online (Sandbox Code Playgroud)

现在为要测试的每个实现创建一个非常小的派生类:

[TestFixture]
public class TestBarAsIFoo : TestIFooBase
{
   public override void SetUp()
   {
      this.Foo = new Bar();
   }
}
Run Code Online (Sandbox Code Playgroud)

编辑:显然NUnit也支持参数化测试夹具,甚至支持带参数类型的通用测试夹具.链接文档中的示例:

[TestFixture(typeof(ArrayList))]
[TestFixture(typeof(List<int>))]
public class IList_Tests<TList> where TList : IList, new()
{
  private IList list;

  [SetUp]
  public void CreateList()
  {
    this.list = new TList();
  }

  [Test]
  public void CanAddToList()
  {
    list.Add(1); list.Add(2); list.Add(3);
    Assert.AreEqual(3, list.Count);
  }
}
Run Code Online (Sandbox Code Playgroud)

这个例子有点简单,因为它有new()类型的约束.但您也可以使用Activator.CreateInstanceIFooTestFixture属性传递实现的构造函数参数.