Created
March 5, 2013 09:26
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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