I have two slightly different variations (TestsA and TestsB) of NUnit parameterized unit tests that use a TestCaseSource to pass arguments to the tests. In each case I'm passing an instance of a class that implements the IDisposable interface (I am using the System.Windows.Forms.Control
class in the examples):
[TestFixture]
[Category("Tests A")]
public static class TestsA
{
private static Control _CONTROL;
[TearDown]
public static void Teardown()
{
_CONTROL.Dispose();
}
private static class TestCases
{
public static IEnumerable<TestCaseData> TestCase1()
{
_CONTROL = new Control { Tag = 1 };
yield return new TestCaseData(_CONTROL);
}
public static IEnumerable<TestCaseData> TestCase2()
{
_CONTROL = new Control { Tag = 2 };
yield return new TestCaseData(_CONTROL);
}
}
[TestCaseSource(typeof(TestCases), nameof(TestCases.TestCase1))]
public static void Test1(Control control)
{
if (control == null)
throw new ArgumentNullException(nameof(control));
Assert.AreEqual(1, (int)control.Tag);
}
[TestCaseSource(typeof(TestCases), nameof(TestCases.TestCase2))]
public static void Test2(Control control)
{
if (control == null)
throw new ArgumentNullException(nameof(control));
Assert.AreEqual(2, (int)control.Tag);
}
}
[TestFixture]
[Category("Tests B")]
public static class TestsB
{
private static class TestCases
{
public static IEnumerable<TestCaseData> TestCase1()
{
yield return new TestCaseData(new Control { Tag = 1 });
}
public static IEnumerable<TestCaseData> TestCase2()
{
yield return new TestCaseData(new Control { Tag = 2 });
}
}
[TestCaseSource(typeof(TestCases), nameof(TestCases.TestCase1))]
public static void Test1(Control control)
{
if (control == null)
throw new ArgumentNullException(nameof(control));
Assert.AreEqual(1, (int)control.Tag);
control.Dispose();
}
[TestCaseSource(typeof(TestCases), nameof(TestCases.TestCase2))]
public static void Test2(Control control)
{
if (control == null)
throw new ArgumentNullException(nameof(control));
Assert.AreEqual(2, (int)control.Tag);
control.Dispose();
}
}
I am trying to come up with the proper way of disposing of the IDisposable instances. The tests in the TestsA class use a TearDown method to do the disposing. In TestsB I am disposing the instance immediately after the Assert. But regardless of how I do it I end up with a CA2000 warning. The warning's description is slightly different for TestsA and TestsB:
TestsA:
Warning CA2000 In method 'TestsA.TestCases.TestCase1()', object 'new Control()' is not disposed along all exception paths. Call System.IDisposable.Dispose on object 'new Control()' before all references to it are out of scope.
TestsB:
Warning CA2000 In method 'TestsB.TestCases.TestCase1()', call System.IDisposable.Dispose on object 'new Control()' before all references to it are out of scope.
My question is: Is there a better alternative for disposing of an object passed to a NUnit test via a TestCaseSource, or can I just ignore the warnings?