mercredi 29 avril 2015

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.

Aucun commentaire:

Enregistrer un commentaire