2009-09-29 67 views
5

我使用nUnit进行测试。我有一套针对IFoo接口运行的测试;测试夹具设置确定要加载和测试的IFoo实施。重复使用多个实现的测试套件?

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

有没有人解决这个问题?

+0

伟大的解决方案。我从来没有想过继承单元测试。并没有意识到nUnit也会测试基类方法。 – Chris 2009-09-30 17:23:46

回答

11

创建包含的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也支持parameterized test fixtures,即使支持带参数类型的通用测试装置。从链接的文档例如:

[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); 
    } 
} 

这个例子是一个有点简单化,因为它具有new()约束的类型。但是您也可以使用Activator.CreateInstance并从TestFixture属性传递IFoo实现的构造函数参数。

+1

+1首先到达那里。 ;) – TrueWill 2009-09-30 01:02:37

+0

参数化测试夹具非常酷!刚刚添加它来测试两个实现,伟大的事情是能够看到每个实现所需的时间。 + 1 – 2013-04-14 23:39:16

1

一个的几种方法来实现:

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(); 
    } 
}