7
votes

I've been trying to learn ASP.NET MVC using the videos posted on the ASP.NET website and I'm running into a problem doing unit testing.

I have a very simple controller that uses LINQ to SQL to get an array of objects:

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";
        using (TrainingLogDataContext dc = new TrainingLogDataContext())
        {
            ViewData.Model = dc.Workouts.ToArray();
        }

        return View();
    }

This fails in NUnit with the following error:

at TrainingLog.Models.TrainingLogDataContext..ctor() in C:\Webs\TrainingLog\TrainingLog\Models\TrainingLog.designer.cs:line 41
at TrainingLog.Controllers.HomeController.Index() in C:\Webs\TrainingLog\TrainingLog\Controllers\HomeController.cs:line 16
at TrainingLogTests.Controllers.HomeControllerTest.Index() in C:\Webs\TrainingLog\TrainingLog.Tests\Controllers\HomeControllerTest.cs:line 23

I guess the problem is that NUnit can't get the connection string for the DataContext from web.config. What's the best way to get around this?

It works fine when I run the page, but the unit test fails in NUnit.

5

5 Answers

5
votes

Copy your connection strings in the web.config project to app.config in your nunit test project.

3
votes

The tack that I took was to mock out the data context. I use a factory to create the data context and inject it into the controller. If the factory is null (which is what happens when the parameterless constructor is called), it creates a default instance of the factory that connects to the database. In my unit tests, I use a factory that creates a fake data context that works in memory. I based my mock data context on code from this blog, though I've extended it to handle objects added to the database via entity sets.

If you don't want to go the mock route (and I would recommend it, though it will take some work up front). You can add an app.config file to your unit test project and put the connection strings for your data context in it.

1
votes

It is best not to access a database from your unit tests as this will result in tests that run so slowly that you'll stop bothering to run the tests. But if you do want to do this you can create an app.config file in your NUnit project and place your connection string there. Sometimes NUnit does not recognise this app.config file, but more details on how to configure it so it does can be found in the answers to "How to initialize ConnectionStrings collection in NUnit".

0
votes

The easiest is to have NUnit installed before you install ASP.NET MVC and then set up the test project when you create the ASP.NET MVC project. You can then create the configuration elements necessary to do what you are attempting.

NOTE: The better way to work with data is to mock it, which means you need to move your LINQ out of your controller, as you cannot easily invert control on a controller.