Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I Execute Code after a Test failed

I am Creating Unit Tests for a Library. This Library Connects to a Datasource and then I am doing some testing Stuff afterwards the Datasource will be disconnected.

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

Here's a Sample to understande the above description:

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

    // Do some Stuff with Asserts

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

Is There any Bestpractice to achieve that?

like image 415
LuckyLikey Avatar asked May 05 '15 10:05

LuckyLikey


1 Answers

If you use resource in other tests, then move it to class fields and use [TestInitialize] and [TestCleanup] to get and free that resource:

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

If you use resource in this test only, then use either 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
    }
}

Or using statement if resource is disposable:

[TestMethod]
public void Test()
{
    using(var datasourceObject = new DatasourceObject("location-string"))
    {
        datasourceObject.Connect();
        // Do some Stuff with Asserts
    }
}
like image 62
Sergey Berezovskiy Avatar answered Sep 28 '22 05:09

Sergey Berezovskiy