How are people unit testing code that uses Linq to SQL [closed]

How are people unit testing code that uses Linq to SQL?


Solution 1:

Update:

Fredrik has put an example solution on how to do unit test linq2sql applications over at his blog. You can download it at:

http://web.archive.org/web/20120415022448/http://iridescence.no/post/DataContext-Repository-Pattern-Example-Code.aspx

Not only do I think its great that he posted an example solution, he also managed to extract interfaces for all classes, which makes the design more decoupled.

My old post:

*I found these blogs that I think are a good start for making the DataContext wrapper: Link1 Link2

They cover almost the same topic except that the first one implements means for extracting interfaces for the tables as well. The second one is more extensive though, so I included it as well.*

Solution 2:

3 years late, but this is how I do it:

https://github.com/lukesampson/LinqToSQL-test-extensions/

No need to write a wrapper or do lots of plumbing, just drop the T4 template next to your .dbml and you get:

  1. An interface for your data context e.g. IExampleDataContext
  2. An in-memory mock for your data context e.g. MemoryExampleDataContext

Both will automatically use the mappings you've already configured in your DBML.

So you can do things like

public class ProductRepo {
    IExampleDataContext DB { get; set };
    public ProductRepo(IExampleDataContext db) {
        DB = db;
    }

    public List<Product> GetProducts() {
        return DB.Products.ToList();
    }
}

and you can call that with either

new ProductRepo(new MemoryExampleDataContext()).GetProducts(); // for testing

or

new ProductRepo(new ExampleDataContext()).GetProducts(); // use the real DB