NUnit test fixture hierarchies

.net, c#, nunit, tdd

Solution

You can use Generic Test Fixtures in NUnit to achive what you want.

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

Problem

I'm trying to create some kind of implementation-agnostic fixture. Say I have the following interface. ``` public interface ISearchAlgorithm { // methods } ``` And I know exactly how it should behave, so I want to run the same set of tests for every derived class: ``` 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 ``` Then I create the following fixtures for each derived class: ``` [TestFixture] public class BinarySearchTests : RootSearchAlgorithmsTests { public BinarySearchTests(): base(new BinarySearchAlgorithm()) {} } [TestFixture] public class NewtonSearchTests : RootSearchAlgorithmsTests { public NewtonSearchTests(): base(new NewtonSearchAlgorithm()) {} } ``` It works well except that both R# test runner and NUnit GUI show the base classes tests as well and of course they fail because there's no appropriate constructor. Why is it even ran if it's not marked with `[TestFixture]`? I guess because of methods with `[Test]` attributes? How can I prevent the base class and it's methods from showing up in results?

Original source