Skip to content

Instantly share code, notes, and snippets.

@RhysC
Created March 5, 2013 09:26
Show Gist options
  • Save RhysC/5089049 to your computer and use it in GitHub Desktop.
Save RhysC/5089049 to your computer and use it in GitHub Desktop.
Testing ASP.net MVC routes does not need to be hard or require external testing libraries. this uses XUnit and Nsubstitue. refactoring out the RequestPath and the assertion and you have a very simple test fixture.
public class RouteFixture
{
private readonly HttpContextBase _httpContextMock;
private readonly RouteCollection _routes;
public RouteFixture()
{
_routes = new RouteCollection();
RouteConfig.RegisterRoutes(_routes);
_httpContextMock = Substitute.For<HttpContextBase>();
}
private RouteData RequestPath(string url)
{
_httpContextMock.Request.AppRelativeCurrentExecutionFilePath.Returns(url);
return _routes.GetRouteData(_httpContextMock);
}
[Fact]
public void RouteDefaultsToHomeWhenNoControllerOrActionProvided()
{
RequestPath("~/").ShouldMatchRoute("Home", "Index");
}
[Fact]
public void HomeIndexGoesToHomeIndex()
{
RequestPath("~/Home/Index").ShouldMatchRoute("Home", "Index");
}
}
public static class RouteTestingExtensions
{
public static void ShouldMatchRoute(this RouteData routeData, string controllerName, string actionName)
{
Assert.NotNull(routeData);
Assert.Equal(controllerName, routeData.Values["Controller"]);
Assert.Equal(actionName, routeData.Values["action"]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment