Unit Test Linq to Sql in ASP.Net MVC with Moq

I have just spent the entire day playing with Moq to unit test an asp.net mvc application I am working with. All I wanted to do is test a “create” method that simply adds a record to the database. So here it goes.

1. I created a Mock Http context to be used by my controller. I modified the Moq version of the MvcMockHelpers class from Scott Hanselman and added two more methods to mock an authenticated user

Note that the identity.Name returns “test” which is the username of an existing user in the database. If I don’t do that then the MembershipProvider.GetUser method will fail.

2. I added a couple of properties to my test class (MessageControllerTest) to make it easy for me to access the controller and view engine in all the test methods

3. I created my test method which is going to call a Create method in my MessageController and pass it a string.

Note that in the verification block, I verify:

  1. The view being rendered
  2. The returned type of the ViewData
  3. Properties on the ViewData

Then I clean up the created message by deleting it from the database.


You must add your connection strings and membership definition in an app.config file in your test project. If you don’t then the default consrtuctor of your DataContext will fail to run because it looks for the connection string in the config file.

I am still wrapping my head around the concept of mocking, so any tips or advice will be appreciated.

Here are some good resources that I found during my struggle to get this to work.

ASP.NET MVC Resources

  1. ASP.NET MVC Framework – Part 2: Testing
  2. ASP.NET MVC Session at Mix08, TDD and MvcMockHelpers

LINQ to SQL Resources

  1. Being Ignorant with LINQ to SQL

Testing and Mocking Resources

  1. Moq: Linq, Lambdas and Predicates applied to Mock Objects
  2. Moq
  3. Rhino Mocks
  4. TDD: Test-Driven Development with Visual Studio 2008 Unit Tests