How to write unit tests for a piece of code that has a data context?

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.");
    }

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.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật