如何处理MSTest中的IDisposable夹具成员?

时间:2012-09-04 22:08:30

标签: c# mstest

我有一个测试类,里面有一些IDisposable项。这是我第一次尝试做这样的事情:

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);
}

不幸的是,ClassCleanup方法在MSTest中必须是static,这意味着没有地方挂钩调用dispose。这是否意味着我需要在每次测试之前和之后重建这些流?

1 个答案:

答案 0 :(得分:2)

简短的回答是肯定的。您需要在每次测试之前重建这些流,并在每次测试后进行处理。使用[TestCleanup]和[TestInitialize]属性很容易。

因此,不要在测试类中构建流:SuppressionDatabaseTest使用[TestInitialize]