views:

132

answers:

1

I have a controller that is working in my site but failing during unit testing. It is pretty simple and depends on Linq to Sql to return a collection of JSON objects.

The Test fails because the DataContext can't find the connection string when called from outside the MVC project.

I had a look in the auto generated code:

public DC():
   base(global::System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString, mappingSource)
 {
  OnCreated();
 }

The web project can find the "myConnectionString" entry in web.config, but the test project can't find it. The error message I got was:

Test method MyMVCApp.Controllers.HomeControllerTest.IndexShouldReturnIssues threw exception:  System.NullReferenceException: Object reference not set to an instance of an object..

I don't want to pass another connection string in from my unit tests because I want to test that the connection string in the web.config works.

Thanks, John

+1  A: 

Add the connection string to the app.config file in your unit test project.

FWIW, I don't actually use a real database in my unit tests (although, I do in integration tests). I wrote about a LINQ-to-SQL implementation that allows mocking on my blog awhile back if you are interested in more info.

tvanfosson
I guess that would work, but I really want to test that the connection string in my web project works, so I guess you could call this an integration test. I wouldn't want to have a situation where the connection string is correct in the test but bad in the site.
John Hoge