Can NUnit run TestCaseSource based tests independently?

107 Views Asked by At

Below tests does not run independently which causes them to fail. In our case, we need to populate a database with relevant data for each case.

Is there a way to let each run on a 'clean' fixture?

[TestFixture]
public class TestSourceTest
{
    int _sum = 0;

    public class T
    {
        public int I { get; }

        public T(int i)
        {
            I = i;
        }

        public override string ToString()
        {
            return I.ToString();
        }
    }
    [TestCaseSource(nameof(TestCases))]
    public void Test(T t)
    {
        _sum += t.I;

        Assert.That(_sum, Is.EqualTo(t.I));
    }

    static IEnumerable<T> TestCases()
    {
        yield return new T(1);
        yield return new T(2);
        yield return new T(3);
    }
}
1

There are 1 best solutions below

0
On BEST ANSWER

The problem isn't TestCaseSource. In NUnit all tests within a fixture have historically used the same fixture instance. This is probably the biggest difference between NUnit and most other frameworks and it's important to be aware of it.

Starting with NUnit 3.13, you have been able to use [FixtureLifeCycle(LifeCycle.InstancePerTestCase)] to override the default and have each test case run in a separate instance. This new feature has had a number of bug fixes since then so you should use the latest release of NUnit (3.13.3 at this writing) if you want to make use of the new attribute.