Unit Testing, LinqToSql and CreateDatabase

Monday, 27 October 2008

Posted by Sébastien Lachance with Comments (0)

When using LinqToSql and unit testing in your application, you can benefit from two handy method calls that will make your life a lot easier.

var db = new DatabaseDataContext();
db.DeleteDatabase();
db.CreateDatabase();

 

You won't need to worry about putting the database in a correct state before each of your test. I call them in my setup part of each unit tests that make use of the database.

If you need to insert some test data, so I used the ExecuteCommand method to execute a sql script.

db.ExecuteCommand(File.ReadAllText(@"..\..\..\..\db\referencedata.sql"));
 
And if you have more than one test that will use this code at a time, you may need to close the connection after the setup.
 
Putting it all together look like this :
var db = new DatabaseDataContext();
db.DeleteDatabase();
db.CreateDatabase();
db.ExecuteCommand(File.ReadAllText(@"..\..\..\..\db\referencedata.sql"));
db.Connection.Close();

 




blog comments powered by Disqus