Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static analysis dispose warning in test class when object is disposed in test cleanup

I have a lot of test classes like this.

[TestClass]
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable")]
public class TestClass
{
    private IDisposable _disposable;

    [TestInitialize]
    public void TestInitialize()
    {
        _disposable = //new disposable object...;
    }

    [TestCleanup]
    public void TestCleanup()
    {
        _disposable.Dispose();
    }

    [TestMethod]
    public void Test1()
    {
        //Uses _disposable
    }

    [TestMethod]
    public void Test2()
    {
        //Uses _disposable
    }

    [TestMethod]
    public void TestN()
    {
        //Uses _disposable
    }
}

Static analysis with FxCop results in the following warning because I do not implement the dispose pattern on my test class.

"CA1001: Types that own disposable fields should be disposable"

Right now I just suppress the message in the source, but I feel like there has to be a better way than cluttering all my tests with SuppressMessageAttribute. This seems like it would be a common pattern in testing - create object for the test and then dispose it after the test. I cannot just implement IDisposable on the test class because only one test object is created for all test methods. I want to dispose this object between every test method.

I know I could create the object in each test and dispose it in the test, but I'd rather continue to use SuppressMessageAttribute over copying and pasting the same code into each test method. It seems like the lesser of the two evils. Is there a better way to create a disposable object before each test and dispose it after each test that doesn't result in warning CA1001?

Thanks for the help in advance.

like image 689
r2_118 Avatar asked Apr 29 '15 17:04

r2_118


1 Answers

The best way I've found is to implement IDisposable in the test class and mark the Dispose method with the TestCleanup attribute.

[TestClass]
public class TestClass : IDisposable
{
    private IDisposable _disposable;

    [TestInitialize]
    public void TestInitialize()
    {
        _disposable = //new disposable object...;
    }

    [TestCleanup]
    public void Dispose()
    {
        _disposable.Dispose();
    }
like image 94
Erik Avatar answered Sep 30 '22 14:09

Erik