How are people unit testing code that uses Linq to SQL

Viewed 16839

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

7 Answers

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.*

Wrap the DataContext, then mock the wrapper. It's the fastest way to get it done, although it requires coding for testing, which some people think smells. But sometimes, when you have dependencies that cannot be (easily) mocked, it's the only way.

Normally, you don't need to test the part of the code that uses LINQ to SQL but if you really want to, you can use the same data sets that you're querying against the server and turn them into in-memory objects and run the LINQ queries against that (which would use the Enumerable methods instead of Queryable).

Another option is to use Matt Warren's mockable version of the DataContext.

You can also get the SQL statements that LINQ to SQL uses by getting them via the debugger (from the IQueryable object), check those manually, and then include them in the automated tests.

Linq makes testing much easier. Linq queries work just as well on Lists as on the Linq-to-sql stuff. You can swap out Linq to SQL for list objects and test that way.

Related