2

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

DaveRandom
  • 87,921
  • 11
  • 154
  • 174
John Hoge
  • 396
  • 1
  • 3
  • 13
  • Look at this answer to see how to effectively and succesfully test with LINQ to SQL: http://stackoverflow.com/questions/4128640/how-to-remove-unit-of-work-functionality-from-repositories-using-ioc/4132186#4132186 – Steven Nov 09 '10 at 20:29

1 Answers1

1

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
  • 524,688
  • 99
  • 697
  • 795
  • 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 Oct 02 '09 at 19:30