单元测试MVC4中的路由/控制器

Pau*_*han 4 c# asp.net-mvc-4

目标:测试给定的url返回给定的控制器函数.

在这个过程中,我已经闯入了路由系统,我无法弄清楚如何测试路由(或者,就此而言,找到与路由相对应的控制器: - /).

示例代码,不起作用:

[Test]       
public void kick_the_tires()
{
   var rc = new RouteCollection();

   Infrastructure.RouteRegistry.RegisterRoutes(rc);

   // get the route corresponding to name.
   var got = rc["name"];

   var expected = //What? foo is an internal type that can't be instantiated.

   Assert.AreEqual(foo, frob);
}
Run Code Online (Sandbox Code Playgroud)

编辑:使用Simon的链接博客文章作为存根类.

[TestCase("/", "~/", "Home", "Index")]
[TestCase("/", "api/command", "Other", "command")]
internal void stub_mocker(string apppath, string route, string expected_controller,\
  string expected_action)
{
  var rc = new RouteCollection();
  Infrastructure.RouteRegistry.RegisterRoutes(rc);

  var httpmock = new StubHttpContextForRouting(
      appPath: apppath,
      requestUrl: route);

  // this always returns null for everything but the Index case.
  var routeData = rc.GetRouteData(httpmock);

  var controller = routeData.Values["controller"];
  var action = routeData.Values["action"];
  Assert.AreEqual(expected_controller, controller);
  Assert.AreEqual(expected_action, action);
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*ger 5

您现在正在测试的是,如果通过路由名称访问路由,将路由添加到集合中,而不是在给定虚拟路径的情况下返回预期路由.您需要使用HttpContext获取RouteCollection返回的路径数据.

最好的方法是使用模拟或存根来获取HttpContext(或HttpContextBase)并调用RouteCollection的GetRouteData(HttpContextBase)方法并检查路由数据.

在Brad Wilson的博客中有一个很好的例子:http: //bradwilson.typepad.com/blog/2010/07/testing-routing-and-url-generation-in-aspnet-mvc.html

编辑:您无法从RouteData本身获取控制器实例.但是,RouteData应该为您提供足够的信息以了解将实例化哪个控制器.例如,如果你有一个MyProject.Controllers.HomeController带有动作的控制器Home,这应该在你的测试中成立(使用xUnit和Moq):

// Prepare
var context = new Mock<HttpContextBase>();
var request = new Mock<HttpRequestBase>();
var response = new Mock<HttpResponseBase>();
var session = new Mock<HttpSessionStateBase>();
var server = new Mock<HttpServerUtilityBase>();

context.SetupGet(c => c.Request).Returns(request.Object);
context.SetupGet(c => c.Response).Returns(response.Object);
context.SetupGet(c => c.Session).Returns(session.Object);
context.SetupGet(c => c.Server).Returns(server.Object);
request.SetupGet(r => r.HttpMethod).Returns("GET");
request.SetupGet(r => r.PathInfo).Returns(String.Empty);
request.SetupGet(r => r.AppRelativeCurrentExecutionFilePath).Returns("~/Home");


var expectedHandler = typeof (HomeController).GetMethod("Index", Type.EmptyTypes);

var data = RouteTable.Routes.GetRouteData(context.Object);

Assert.NotNull(data);

var handler = (MethodInfo) data.DataTokens["actionMethod"];
Assert.Equal(expectedHandler, handler);
Run Code Online (Sandbox Code Playgroud)