I am testing a module where every test class share the same behavior:
I've decided to use TestInitialize and TestCleanup to execute the Begin and Rollback of transactions respectively.
The strait forward approach would be writing the TestInitialize/TestCleanup in a parent class but that is not going to work with this testing framework.
The work around for this was to use partial classes. This approach seems to viable in my case because my test classes are mainly stateless. Event not being the ideal solution it at least saved me a couple of copy/paste actions.
Anyone knows a better way to do this?
Here is a sample of the partial class solution:
In my case I test each module separately and for this example I will use the Sales module:
SalesTest.cs file:
[TestClass]
public partial class SalesTest
{
[TestInitialize]
public void Setup()
{
//begin transaction
}
[TestCleanup]
public void Cleanup()
{
//rollback transaction
}
}
SalesTest.Order file:
public partial class SalesTest
{
[TestMethod]
public void SaveOrder_OnlyRequiredValuesFilled_SuccessfullySaved()
{
//Run some SQL queries
}
}
Looks like you're using Microsoft.VisualStudio.TestTools.UnitTesting
framework. I don't see any problem using a base class for Cleanup and Initialize.
E.g.
[TestClass]
public class TestDemo : BaseTests
{
[TestMethod]
public void SaveOrder_OnlyRequiredValuesFilled_SuccessfullySaved()
{
//Run some SQL queries
}
}
[TestClass]
public abstract class BaseTests
{
[TestInitialize]
public void Setup()
{
Console.WriteLine("Setup executed.");
//begin transaction
}
[TestCleanup]
public void Cleanup()
{
Console.WriteLine("Cleanup executed.");
//rollback transaction
}
}
This will work fine and I can inherit the BaseTest
to any Test and the Intiailize and Cleanup will execute before and after any test.