Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC TDD with LINQ and SQL database

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?

like image 705
ddd Avatar asked Jan 06 '09 14:01

ddd


4 Answers

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.

like image 55
tvanfosson Avatar answered Oct 23 '22 07:10

tvanfosson


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.

like image 33
ddd Avatar answered Oct 23 '22 07:10

ddd


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.

like image 1
Ryan Lanciaux Avatar answered Oct 23 '22 05:10

Ryan Lanciaux


Consider these methods on DataContext:

http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.createdatabase.aspx

http://msdn.microsoft.com/en-us/library/system.data.linq.datacontext.executecommand(v=VS.100).aspx

like image 1
Amy B Avatar answered Oct 23 '22 07:10

Amy B