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)
            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;
                        XYZTableIdDeleted = modifiedXYZRecord .ID;

            return XYZTableIdDeleted ;
        catch (Exception)



And here's the test method I am using to test it:

    public void DeleteXYZTest()

        string exceptionName = String.Empty;


            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);

        Assert.Fail("No exception was thrown.");
  • Are you using Linq to SQL stuff? If so, perhaps this might be of interest.
    – J Trana
    Jan 10, 2015 at 4:26

1 Answer 1


In order for unit tests to work you have to be able to mock all the external dependencies to your code (otherwise you're doing an integration test). Your problem is you have direct dependencies to your data access implementations. This is coupled with the problem that your handler is both doing its handling work and is responsible for creating your data access classes.

What you want to be doing is abstracting your data layer. This is most often done with what's called Repository pattern. It doesn't have to be, but the point is you need a layer of abstraction between your handler and your data access. Then generally you would pass this dependency in from the thing that's calling the handler. This is most often achieved with dependency injection frameworks, but again, you don't necessarily need to go that far.

Once you no longer have a dependency on a concrete class, you can use a mocking framework to mock the data access dependencies. Try Rhino or Moq, there's a lot of different ones. You would mock the interface you send into the handler, and specify what the handler does when you call it. This removes the variability of what your dependencies do and let's you focus solely on the functionality of the code you're testing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.