views:

888

answers:

5

I am trying to start a new MVC project with tests and I thought the best way to go would have 2 databases. 1 for testing against and 1 for when I run the app and use it (also test really as it's not production yet).

For the test database I was thinking of putting create table scripts and fill data scripts within the test setup method and then deleting all this in the tear down method.

I am going to be using Linq to SQL though and I don't think that will allow me to do this?

Will I have to just go the ADO route if I want to do it this way? Or should I just use a mock object and store data as an array or something?.

Any tips on best practices?

How did Jeff go about doing this for StackOveflow?

+4  A: 

What I do is define an interface for a DataContext wrapper and use an implementation of the wrapper for the DataContext. This allows me to use an alternate, fake DataContext implementation in my tests (or mock it, if easier). This abstracts the database out of my unit tests completely. I found some starter code at http://andrewtokeley.net/archive/2008/07/06/mocking-linq-to-sql-datacontext.aspx, although I've extended it so that it handles the validation implementations on my entity classes.

I should also mention that I have a separate staging server for QA, so there is live testing of the entire system. I just don't use an actual database in my unit testing.

tvanfosson
I use that same datacontext mocking code and it works nicely
Bramha Ghosh
+1  A: 

You may want to find some other way around actually hitting the database for your unit tests because it takes a lot more time. That being said, have you considered using Migrations for creating / deleting your tables instead of using sql scripts? RikMigrations is what I have been using to create my database so I can easily revision all of my code in one place. Justin Etheredge has a great article on using RikMigrations.

Ryan Lanciaux
A: 

I checked out the link from tvanfosson and RikMigrations and after playing about with them I prefer the mocking datacontext method best. I realised I don't need to create tables and drop them all the time.

After a little more research I found Stephen Walther's article http://stephenwalther.com/blog/archive/2008/08/17/asp-net-mvc-tip-33-unit-test-linq-to-sql.aspx which to me seems easier and more reliable.

So I am going with this implementation.

Thanks for the help.

dean nolan
A: 

This article gives example of mocking linq to sql with typemock.

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

Yack