views:

121

answers:

5

What is the best and easiest way to unit test a Class that uses LINQ to SQL and returns back a decimal, is it by Mocking? If so how do I go about this?

A: 

Here's an article about mocking the LINQ to SQL DataContext. It appears to be what you're looking for because it states:

So [usually] it isn’t really possible to unit test your Linq to SLQ queries without being connected to the underlying data source – not ideal. But fear not, here is a generic solution to this problem.

And it summarizes with

So we now have a way to test our LINQ to SQL queries within our CustomerController class without relying on a database bound DataContext

Additionally (after the above is working) the NMock library helps you program mock objects for situations and might be used to program against this in a more formal way, or to integrate with other mocks (I haven't tried).

John K
A: 

You should wrap the call to the LINQ to SQL method in a class that implements an interface, so that mocking is possible.

Anyway, in .NET 4, an ITable interface is defined that will help a lot on using mocks for testing scenarios that use LINQ to SQL (http://damieng.com/blog/2009/06/01/linq-to-sql-changes-in-net-40). Another option is to mock the DataContext itself, see for example here: http://andrewtokeley.net/archive/2008/07/06/mocking-linq-to-sql-datacontext.aspx

Konamiman
+1  A: 

Only mock types you own.

Mark Needham has a short blog entry on why.

Oded
A: 

Hey check out this one.......

http://blog.benhall.me.uk/2007/11/how-to-unit-test-linq-to-sql-and.html

bala3569
A: 

I wasn't able to come up with comfortable mocking solution for unit testing with Linq to SQL, so I went a different route.

I created a test database with known values in it to test against. Then, because you don't want to have your tests changing the contents of your data, I employed the XtUnit extension for NUnit: http://weblogs.asp.net/rosherove/archive/2004/10/05/238201.aspx

This extension magically reverts any changes your test makes to the database once your test has completed.

I won't lie, this solution is kinda ugly. However, it also doesn't require you to come up with a bizarro mocking concept. Once you have your test data established, it is very easy to write your tests. All your tests need is to make sure your class inherits from ExtensibleFixture, and to mark your test(s) with the [DataRollBack] attribute, and XtUnit will do the rest.

grimus