Testing MVC module using Linq to Sql

I have a controller that works on my site but doesn't work during unit testing. It's pretty simple and relies on Linq to Sql to return a collection of JSON objects.

The test fails because the DataContext cannot find the connection string when called due to the MVC project.

I looked at 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 the web.config, but the test project cannot find it. The error message I received 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 in a different connection string from my unit tests because I want to test that the connection string in the web.config is working.

Thanks, John

+2


source to share


1 answer


Add a connection string to your 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 you to mock the blog a while ago if you're interested in more details.

+1


source







All Articles