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");

Advertisements
%d bloggers like this: