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
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With