Unit testing LINQ to SQL in ASP.NET MVC Web Applications

If you want to unit test LINQ to SQL statements in an ASP.NET MVC application you most likely will get a NullReference Exception that is thrown when trying to instantiate the DataContext. That’s because the standard constructor of the DataContext is trying to get the database connection string from the current .config file.

To solve that problem, without changing the code and specifying the connection string explicitly in the DataContext’ constructor, you just have to add an App.config file to your test project and copy the contents (or at least the configuration -> connection strings section) from the Web.config to it.

Second you have to adjust the AttachDbFilename property in the connection string to point again to your actual .mdf file. Since you cannot use relative paths in the connection string, you have to put in the full path. Here’s an interesting excerpt from MSDN:

When DataDirectory is used, the resulting file path cannot be higher in the directory structure than the directory pointed to by the substitution string. For example, if the fully expanded DataDirectory is C:\AppDirectory\app_data, then the sample connection string shown above works because it is below c:\AppDirectory. However, attempting to specify DataDirectory as |DataDirectory|\..\data will result in an error because \data is not a subdirectory of \AppDirectory.

However we have the option to change where the |DataDirectory| shall point to. So you don’t have to touch the connection string directly. To do that you just have to call the AppDomain.SetData Method in the test project.

AppDomain.CurrentDomain.SetData("DataDirectory", @"C:\Projects\MyProject\MyProject\App_Data");


One Response to “Unit testing LINQ to SQL in ASP.NET MVC Web Applications”

  1. smartcaveman Says:

    Isn’t what you’re describing an integration test rather than a unit test? ( http://stackoverflow.com/questions/5357601/whats-the-difference-between-unit-tests-and-integration-tests , http://en.wikipedia.org/wiki/Integration_testing )

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: