测试失败后如何执行代码

How do I Execute Code after a Test failed

我正在为库创建单元测试。这个库连接到一个数据源,然后我正在做一些测试,之后数据源将被断开。

If one of the Tests fails, the Method is Terminated and I dont get to execute the Disconnection Function.

这里有一个例子来理解上面的描述:

[TestMethod]
public void Test()
{
    var datasourceObject = new DatasourceObject("location-string");
    datasourceObject.Connect();

    // Do some Stuff with Asserts

    datasourceObject.Disconnect(); // must be executed
}

是否有实现该目标的最佳实践?

如果您在其他测试中使用资源,则将其移动到 class 字段并使用 [TestInitialize][TestCleanup] 获取并释放该资源:

private Foo datasourceObject;

[TestInitialize]
public void TestInitialize()
{
    this.datasourceObject = new DatasourceObject("location-string");
    this.datasourceObject.Connect();
}

[TestMethod]
public void Test()
{
    // Do some Stuff with Asserts
}

[TestCleanup]
public void TestCleanup()
{
    this.datasourceObject.Disconnect();
}

如果您仅在此测试中使用资源,则使用 try..finally

[TestMethod]
public void Test()
{
    try
    {
        var datasourceObject = new DatasourceObject("location-string");
        datasourceObject.Connect();
        // Do some Stuff with Asserts
    }
    finally
    {
        datasourceObject.Disconnect(); // must be executed
    }
}

using 语句如果资源是一次性的:

[TestMethod]
public void Test()
{
    using(var datasourceObject = new DatasourceObject("location-string"))
    {
        datasourceObject.Connect();
        // Do some Stuff with Asserts
    }
}