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.
Copy your connection strings in the web.config project to app.config in your nunit test project.
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.
This template and instructions helped me getting this up and running: http://johnnycoder.com/blog/2009/04/01/aspnet-mvc-test-template-project-for-nunit-and-moq/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With