2009-09-29 66 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(); 
    } 
}