Unit testing 在多个实现中重用测试套件?
我在用努伊特测试。我有一套针对我的IFoo接口运行的测试;测试夹具设置决定加载和测试哪个IFoo实现 我试图找出如何在IFoo实现列表上运行同一个套件,但在不手动修改设置的情况下,无法测试所有实现Unit testing 在多个实现中重用测试套件?,unit-testing,nunit,Unit Testing,Nunit,我在用努伊特测试。我有一套针对我的IFoo接口运行的测试;测试夹具设置决定加载和测试哪个IFoo实现 我试图找出如何在IFoo实现列表上运行同一个套件,但在不手动修改设置的情况下,无法测试所有实现 有人解决过这个问题吗?创建一个基本测试类,其中包含IFoo实现之间共享的测试,如下所示: // note the absence of the TestFixture attribute public abstract class TestIFooBase { protected IFoo Fo
有人解决过这个问题吗?创建一个基本测试类,其中包含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());
}
}
现在,为要测试的每个实现创建一个非常小的派生类:
[TestFixture]
public class TestBarAsIFoo : TestIFooBase
{
public override void SetUp()
{
this.Foo = new Bar();
}
}
编辑:显然,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);
}
}
[TestFixture(typeof(ArrayList))]
[测试夹具(类型(列表))]
公共类IList_测试,其中TList:IList,new()
{
私人名单;
[设置]
public void CreateList()
{
this.list=new TList();
}
[测试]
公共无效CanAddToList()
{
list.Add(1);list.Add(2);list.Add(3);
Assert.AreEqual(3,list.Count);
}
}
这个例子有点简单,因为它对类型有
new()
约束。但是您也可以使用Activator.CreateInstance
并从TestFixture
属性传递IFoo
实现的构造函数参数。实现此目的的几种方法之一:
public interface IFoo
{
string GetName();
}
public class Foo : IFoo
{
public string GetName()
{
return "Foo";
}
}
public class Bar : IFoo
{
public string GetName()
{
return "Bar"; // will fail
}
}
public abstract class TestBase
{
protected abstract IFoo GetFoo();
[Test]
public void GetName_Returns_Foo()
{
IFoo foo = GetFoo();
Assert.That(foo.GetName(), Is.EqualTo("Foo"));
}
}
[TestFixture]
public class FooTests : TestBase
{
protected override IFoo GetFoo()
{
return new Foo();
}
}
[TestFixture]
public class BarTests : TestBase
{
protected override IFoo GetFoo()
{
return new Bar();
}
}
伟大的解决方案。我从未想过要继承单元测试。而且从未意识到nUnit也会测试基类方法。参数化测试夹具非常酷!刚刚添加它来测试两个实现,最棒的事情是能够看到每个实现完成其工作所需的时间1.