Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a Linq2Sql DataContext

I have a Lin2Sql DataContext that I am using to get all my data from a sql database however I am struggling to find a way to successfully Mock this so that I can create relevant Unit Tests.

In my data access objects that I am wanting to test I am refreshing the context each time and I am finding it difficult to find a simple suitable way to mock this.

Any help with this matter will be greatly appreciated.

like image 932
Grenter Avatar asked Aug 01 '12 11:08

Grenter


1 Answers

Mocking the linq-to-sql context is indeed a huge task. I usually work around it by letting my unit tests run against a separate database copy, with data specially crafted to fit the unit tests. (I know it can be argued that it's no longer unit tests, but rather integration tests, but I don't care as long as I get the code tested).

To keep the database in a known state I wrap each test in a TransactionScope which is rolled back at the end of the test. That way the state of the database is never changed.

A sample test method looks like this:

[TestMethod]
public void TestRetire()
{
    using (TransactionScope transaction = new TransactionScope())
    {
        Assert.IsTrue(Car.Retire("VLV100"));
        Assert.IsFalse(Car.Retire("VLV100"));

        // Deliberately not commiting transaction.
    }
}

The code is from a blog post about the method I wrote some time ago: http://coding.abel.nu/2011/12/using-transactions-for-unit-tests/

like image 113
Anders Abel Avatar answered Oct 03 '22 23:10

Anders Abel