Unit Testing with Linq to Sql
I am working on a small personal project to learn some new things. One my objectives is to follow the test first methodology. Something I just discovered was using SQLExpress to dynamically create databases on the fly, which makes setting up unit tests really easy. You can provide a connection string to a local database create it and add any data required for testing. When you are finished just delete the database.
Using Nunit you can structure your tests in a couple of ways, you can have a setup per class, or you can do setup per test. This is accomplished with the TestFixtureSetUp, and SetUp attributes respectively. When doing setup you should also do clean up, this is done via TestFixtureTearDown, and TearDown.
private CollectionsDataContext db = null;
public void SetupTests()
db = new CollectionsDataContext(Utilities.CollectionDb);
var user = new aspnet_User
ApplicationId = System.Guid.NewGuid(),
UserId = System.Guid.NewGuid(),
UserName = "TestUser",
LastActivityDate = DateTime.Now,
LoweredUserName = "testuser"
public void Cleanup()
public void GetUser()
var user = from u in db.aspnet_Users select u;
foreach (var user1 in user)
One thing not to do is delete the database from the file system, it will then be in never never land. Using the Linq DeleteDatabase method removed the files from removed the files from the file system.
The database location is pulled from the app.config which currently looks like this for the Nunit tests.
In the actual application it will point to a database on a server.