Billy ONeal
Billy ONeal

Reputation: 106549

How does one deal with IDisposable fixture members in MSTest?

I have a test class which has some IDisposable items inside of it. This was my first attempt at doing something like this:

private MemoryStream toolExampleMs;
private MemoryStream issueClassExampleMs;
private MemoryStream issueTypeExampleMs;
private MemoryStream uniqueIdExampleMs;

private Check exampleCheck;

public SuppressionDatabaseTest()
{
    this.toolExampleMs = new MemoryStream(Encoding.UTF8.GetBytes(toolExample));
    this.issueClassExampleMs = new MemoryStream(Encoding.UTF8.GetBytes(toolExample));
    this.issueTypeExampleMs = new MemoryStream(Encoding.UTF8.GetBytes(issueTypeExample));
    this.uniqueIdExampleMs = new MemoryStream(Encoding.UTF8.GetBytes(uniqueIdExample));

    this.exampleCheck = new Check();
    this.exampleCheck.IssueClass = "FooBarClass";
    this.exampleCheck.IssueType = "FooBarType";
    this.exampleCheck.Key = "FooBarExactWith?Unicode";
}

[ClassCleanup]
public void CleanupAll() // Error: CleanupAll has the wrong signature
{
    toolExampleMs.Dispose();
    issueClassExampleMs.Dispose();
    issueTypeExampleMs.Dispose();
    uniqueIdExampleMs.Dispose();
}

[TestCleanup]
public void Cleanup()
{
    this.toolExampleMs.Seek(0, SeekOrigin.Begin);
    this.issueClassExampleMs.Seek(0, SeekOrigin.Begin);
    this.issueTypeExampleMs.Seek(0, SeekOrigin.Begin);
    this.uniqueIdExampleMs.Seek(0, SeekOrigin.Begin);
}

Unfortunately, the ClassCleanup method must be static in MSTest, which means there's no place to hook the calls to dispose. Does this mean I need to reconstruct these streams before and after every individual test?

Upvotes: 4

Views: 1456

Answers (1)

Kyle C
Kyle C

Reputation: 1637

Short answer is yes. You will need to reconstruct these streams before each test and dispose them after each test. This is easy with the [TestCleanup] and [TestInitialize] attributes.

So instead of constructing your streams in your test class: SuppressionDatabaseTest use [TestInitialize]

Upvotes: 4

Related Questions