C# Using TestCleanup in MSTest

If like me you put simplicity as the key priority factor when developing, your likely not a fan of unit test mocking frameworks as they add additional and for the majority of the time unnecessary complexity to your applications.


Having your unit tests coupled to your database is not a bad thing. There are a lot of articles online that push decoupling to an extreme and encourage the use of mocking frameworks to unit test methods that dependant on your database to run with mocked objects. Its an interesting and clever idea but unnecessary if your keen on the KISS principle and favour simplicity.


I setup my development environments with a dev (development), staging (preview/staging area) and Live (production) databases. When running unit tests it will always be configured to point to my dev database. One of the downsides of unit testing couples methods with the database is that it will update your dev database with updates/inserts and deletes as you test your application. To overcome this I create a stored procedure called "Usp_DeleteUnitTestData" that will clear out test data to restore my database to the same sate it was in prior to running tests.


MSTest offers 2 great options for executing cleanup tests either after each test or after all tests have run.


Let me show you how I have setup my unit tests for IntermittentBug. This example uses the test "TestGetArticleAnswers"

 

[TestClass]
public class TestCleanupInMSTest : TestBase
{
	[TestMethod]
	public void TestGetArticleAnswers()
	{
		List<tbl_Answer> ArticleAnswers = AnswerLogic.GetArticleAnswers(_TestArticleID);
		Assert.IsTrue(ArticleAnswers.Count > 0);
	}
}

All my test class's inherit a test base class. This is best practise as its useful to store the clean-up methods as well as a great place for global test variables. 

[TestClass]
public class TestBase
{
	protected int _TestUserID = 3;
	protected int _TestArticleID = 1;

	/// <summary>
	/// This will run after each test
	/// </summary>
	[TestCleanup()]
	public void Cleanup_AfterEachTest()
	{
		using (var DB = new IntermittentBug_DBEntities())
		{
			DB.Usp_DeleteUnitTestData();
		}
	}

	/// <summary>
	/// This will run after all tests are complete
	/// </summary>
	[AssemblyCleanup()]
	public static void Cleanup_AfterAllTests()
	{
		using (var DB = new IntermittentBug_DBEntities())
		{
			DB.Usp_DeleteUnitTestData();
		}
	}
}

 

I have been using this unit testing method successfully on many large scale enterprise applications so give it a go with your project.


JGilmartin Profile Image

JGilmartin

Technical Architect at Pinewood Technologies

Rating: 2890

C# Expert

Offline


Tutorial Statistics
  • Views: 1299
  • Comments: 0
  • Author: JGilmartin (2890)
  • Date: 27/12/2016 12:06
Tags
C# .NET Visual Sudio Unit Testing

© 2016 - 2018 - IntermittentBug