NUnit测试夹具层次结构

Gro*_*ozz 2 .net c# tdd nunit

我正在尝试创建某种与实现无关的夹具.

说我有以下界面.

public interface ISearchAlgorithm
{
    // methods
}
Run Code Online (Sandbox Code Playgroud)

我确切地知道它应该如何表现,所以我想为每个派生类运行相同的测试集:

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
Run Code Online (Sandbox Code Playgroud)

然后我为每个派生类创建以下灯具:

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

[TestFixture]
public class NewtonSearchTests : RootSearchAlgorithmsTests
{
    public NewtonSearchTests(): base(new NewtonSearchAlgorithm()) {}
}
Run Code Online (Sandbox Code Playgroud)

它运行良好,除了R#test runner和NUnit GUI都显示基类测试,当然它们失败,因为没有合适的构造函数.

如果它没有标记,为什么它甚至会跑[TestFixture]?我猜是因为有[Test]属性的方法?

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

dav*_*d.s 7

您可以在NUnit中使用通用测试夹具来实现您的需求.

[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
}
Run Code Online (Sandbox Code Playgroud)