Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does one deal with IDisposable fixture members in MSTest?

Tags:

c#

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?

like image 710
Billy ONeal Avatar asked Oct 21 '25 13:10

Billy ONeal


1 Answers

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]

like image 140
Kyle C Avatar answered Oct 23 '25 04:10

Kyle C