Friday, April 20, 2012

Test with database call and rollback your changes

This example is for MSTest. You can do the same thing for Nunit. We will have test init and test cleanup calls. Those will be called before and after each test. Whenever you define transaction scope, it will wrap your calls inside. Default scope option is Required.

We will rollback our changes at test cleanup. Of course, it will lock your records until your test completes. You could not do select statement from test table for all rows. You can read my previous post about transactions and locks in SQL.




        [TestInitialize()]
        public void MyTestInitialize()
        {
            //without any scope option. Default is Required scope option and Serializable trans type
             testTransScope = new TransactionScope();
        }
 
        [TestCleanup()]
        public void MyTestCleanup()
        {
             Console.WriteLine("Cleanup trans rollback");
             Transaction.Current.Rollback();
             testTransScope.Dispose();
        }

Our test method to add object and get that. This object will not be there after test is complete. However, your next identity value on that table will not be same.:


 [TestMethod()]
        public void CreateTest()
        {
            MailJobController target = new MailJobController();
            string name = "status for Omer" + Guid.NewGuid().ToString().Substring(0, 5);
            int id = target.AddStatus(name);
 
            Assert.IsTrue(id > 0);
 
             
        }

Our Controller method that we are testing:



 public int AddStatus(string dessert)
       {
            
               try
               {
                   // ...
                   StatusDefinition statusDefinition = new StatusDefinition() {Name = dessert};
                   db.StatusDefinitions.AddObject(statusDefinition);
                   db.SaveChanges();
                   Console.WriteLine("object id:"+statusDefinition.StatusDefinitionId);
                   
                   return statusDefinition.StatusDefinitionId;
               }
               catch (Exception ex)
               {
                   Console.WriteLine(ex.ToString());
               }
            
 
           return -1;
       }
 
        public string GetStatus(int id)
        {
            var obj = db.StatusDefinitions.Where(a => a.StatusDefinitionId == id).FirstOrDefault();
            if (obj != null)
                return obj.Name;
 
            return null;
        }

  

No comments:

Post a Comment

Hey!
Let me know what you think?