tags:

views:

183

answers:

2

I am testing my routes in an mvc app. I have the following code:

using System.Web.Routing;
using MvcContrib.TestHelper;
using NUnit.Framework;
using web;
using web.Controllers;

namespace tests.web.Routes
{
    [TestFixture]
    public class routeTests
    {
        [Test]
        public void Route_POSURL_MapsToPOSIndex()
        {
            MvcApplication.RegisterRoutes(RouteTable.Routes);
            "~/POS".ShouldMapTo<POSController>(x => x.Index());
        }

        [Test]
        public void Route_POSGetItem_MapsToPOSGetItem()
        {
            MvcApplication.RegisterRoutes(RouteTable.Routes);
            "~/POS/GetItem/12345".ShouldMapTo<POSController>(x => x.GetItem());
        }
    }
}

However, the 2nd test fails stating: System.ArgumentException: A route named 'Default' is already in the route collection. Route names must be unique.

If I run either test individually they run fine. Obviously NUnit is sharing my Routing table across tests. Why?

I know I can put my RegisterRoutes call in a TestFixtureSetup method but this doesn't answer the issue and I'd like to know what I am missing.

Am I just missing something? How come I can't find this question anywhere else on the net?

Thanks! Matt

+1  A: 

I don't think it's NUnit sharing the routes - I do believe that is how ASP.NET MVC works. FWIW, when testing my routes I usually put RegisterRoutes in [TestFixtureSetup]. You'd probably be okay to just do the same thing.

Tom Opgenorth
A: 

I found this great article from Martin Fowler which explains what is going on: http://martinfowler.com/bliki/JunitNewInstance.html

Kudos to the xUnit Test Patterns book, as it's the one that led me to the article.

I don't know if it's because I used to be a Java guy or if I just made some assumptions. JUnit creates a new TestCase object for every single method when you run tests. That means that even global variables are reset for every single test method and are not shared.

This is not the case with NUnit. NUnit creates only one TestCase object, thus any global variables are shared. Tom, you're right in the fact that MVC creates the global variable for my routes, however, NUnit does not dump this and create a new one for each test like most other xUnit frameworks do.

I have placed the register routes code in the TestFixtureSetup method, and it works of course. I'm glad that I understand what's going on now.

Matt Penner