NUnit测试夹具层次结构

时间:2012-04-19 08:56:39

标签: c# .net tdd 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#test runner和NUnit GUI都显示基类测试之外,它运行良好,当然它们都失败了,因为没有合适的构造函数。

如果它没有标记为[TestFixture],为什么还要运行?我猜是因为有[Test]属性的方法?

如何防止基类及其方法显示在结果中?

1 个答案:

答案 0 :(得分:7)

您可以在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
}
相关问题