2012-04-19 95 views
1

我正在嘗試創建某種與實現無關的夾具。NUnit測試夾具層次結構

說我有以下接口。

public interface ISearchAlgorithm 
{ 
    // methods 
} 

而且我知道它到底應該如何表現,所以我想運行在同一組測試的每一個派生類:

public class RootSearchAlgorithmsTests 
{ 
    private readonly ISearchAlgorithm _searchAlgorithm; 

    public RootSearchAlgorithmsTests(ISearchAlgorithm algorithm) 
    { 
     _searchAlgorithm = algorithm; 
    } 

    [Test] 
    public void TestCosFound() 
    { 
     // arrange 
     // act with _searchAlgorithm 
     // assert 
    } 

    [Test] 
    public void TestCosNotFound() 
    { 
     // arrange 
     // act with _searchAlgorithm 
     // assert 
    } 
    // etc 

然後,我爲每一個派生類中的下列燈具:

[TestFixture] 
public class BinarySearchTests : RootSearchAlgorithmsTests 
{ 
    public BinarySearchTests(): base(new BinarySearchAlgorithm()) {} 
} 

[TestFixture] 
public class NewtonSearchTests : RootSearchAlgorithmsTests 
{ 
    public NewtonSearchTests(): base(new NewtonSearchAlgorithm()) {} 
} 

它運作良好,除了兩個R#測試運行和NUnit GUI顯示基類測試以及,當然他們失敗,因爲沒有合適的構造函數。

爲什麼它沒有標記[TestFixture]?我猜是因爲具有[Test]屬性的方法?

如何防止基類及其方法在結果中顯示?

回答

6

您可以在NUnit中使用Generic Test Fixtures來達到您想要的效果。

[TestFixture(typeof(Implementation1))] 
[TestFixture(typeof(Implementation2))] 
public class RootSearchAlgorithmsTests<T> where T : ISearchAlgorithm, new() 
{ 
    private readonly ISearchAlgorithm _searchAlgorithm; 

    [SetUp] 
    public void SetUp() 
    { 
     _searchAlgorithm = new T(); 
    } 

    [Test] 
    public void TestCosFound() 
    { 
     // arrange 
     // act with _searchAlgorithm 
     // assert 
    } 

    [Test] 
    public void TestCosNotFound() 
    { 
     // arrange 
     // act with _searchAlgorithm 
     // assert 
    } 
    // etc 
} 
+0

該解決方案有一個空的構造函數需求的缺點,我希望避免即使在我的代碼中顯示的構造函數在當時是空的。我想我可以傳入某種構造函數,我應該研究一下。謝謝。 – Grozz 2012-04-19 09:18:58

+0

我認爲你可以使用帶參數的通用測試夾具來傳遞參數給你的構造函數。 – 2012-04-19 10:32:05