I am new to unit testing and using Microsoft's unit testing library for following piece of code. When I execute the code normally it executes fine, however when I run unit test written for this code I get a nullreference error at the point of datacontext initialization.
Following is a method similar to the one i am trying to test:
public int DeleteXYZTableRecord(int Id) { try { int XYZTableIdDeleted = -1; using (System.Transactions.TransactionScope scope = new System.Transactions.TransactionScope(System.Transactions.TransactionScopeOption.Required, new System.Transactions.TransactionOptions { IsolationLevel = System.Transactions.IsolationLevel.Snapshot })) { if (Id <= 0) { throw new ArgumentException(InvalidIdMessage); } using (DBDataContext context = new DBDataContext()) //**exception occurs here** {//block inside using is irrelevant as its never executed due to the exception XYZTable modifiedXYZRecord = context .XYZTables.Where(x => x.ID.Equals(Id)).FirstOrDefault(); if (modifiedXYZRecord == null) throw new NullReferenceException(RecordNotFoundMessage); if (modifiedXYZRecord .pqrRecords == null && modifiedXYZRecord .pqrRecords == null) { modifiedXYZRecord .status = 0; context.SubmitChanges(); XYZTableIdDeleted = modifiedXYZRecord .ID; } } scope.Complete(); } return XYZTableIdDeleted ; } catch (Exception) { throw; } }
And here's the test method I am using to test it:
[TestMethod] public void DeleteXYZTest() { string exceptionName = String.Empty; try { var target = new DBService.UpdateData .XYZDBHandler(); // Access the data int inputId = 1; int expectedOutputId = 1; int actual = target.DeleteXYZTableRecord(inputId); Assert.AreEqual(expectedOutputId, actual, "x:<{0}> y:<{1}>", new object[] { expectedOutputId, actual }); } catch (Exception e) { StringAssert.Contains(e.Message, DBService.UpdateData.XYZDBHandler.RecordNotFoundMessage); return; } Assert.Fail("No exception was thrown."); }