| Greg's profileGreg Olsen - Yellow Duck...PhotosBlogLists | Help |
|
December 09 System.TransactionScope with Unit Testing for both NUnit & Visual Studio Unit TestingOne good thing about using System.Transactions with a unit test is the ability to perform a database unit test which then performs a rollback once the test is completed. (1) To create a unit test for NUnit with database rollback, simply add a 'using' statement similar to the example below. Note: you need to add a reference to your project to the System.Transactions namespace. Then add 'using System.Transactions;' to your class (.cs) file. You will also need the NUnit.Framework dll added as a project reference and also 'using NUnit.Framework;' to your class (.cs) 1: [Test]2: public void BlogInsert() 3: { 4: using (TransactionScope scope = new TransactionScope()) 5: {6: DateTime postedDate = new DateTime(2006, 11, 23); 7: string title = "XML Notepad 2006"; 8: string contents = "this is the contents from the blog"; 9: string blogUrl = "http://yellowduckguy.spaces.live.com/"; 10: 11: int expectedRowsAffected = 1; 12: int actualRowsAffected = BlogDataAccess.BlogAdapterInsert(postedDate, title, contents, blogUrl); 13: 14: Assert.AreEqual(expectedRowsAffected, actualRowsAffected); 15: } 16: }The key lines in the above code is line 4. This is where we add the 'using (TransactionScope ....' statement in order to wrap the statement into a transaction and allow the code to rollback against the database (I have been using this against SQL Server Database). (2) To create a unit test for Visual Studio with database rollback, simply change the the unit test attribute from [Test] to [TestMethod] and make sure you have reference to 'using Microsoft.VisualStudio.TestTools.UnitTesting;' 1: [TestMethod]2: public void BlogInsert() 3: { 4: using (TransactionScope scope = new TransactionScope()) 5: {6: DateTime postedDate = new DateTime(2006, 11, 23); 7: string title = "XML Notepad 2006"; 8: string contents = "this is the contents from the blog"; 9: string blogUrl = "http://yellowduckguy.spaces.live.com/"; 10: 11: int expectedRowsAffected = 1; 12: int actualRowsAffected = BlogDataAccess.BlogAdapterInsert(postedDate, title, contents, blogUrl); 13: 14: Assert.AreEqual(expectedRowsAffected, actualRowsAffected); 15: } 16: }Trackbacks (1)The trackback URL for this entry is: http://yellowduckguy.spaces.live.com/blog/cns!DA380C13569E8907!128.trak Weblogs that reference this entry
|
|
|