gpt4 book ai didi

c# - MVC4 中的单元测试路由/ Controller

转载 作者:太空狗 更新时间:2023-10-30 00:53:14 25 4
gpt4 key购买 nike

目标:测试给定的 url 是否返回给定的 Controller 函数。

在这个过程中,我闯入了路由系统,我不知道如何测试路由(或者,就此而言,找到与路由对应的 Controller :-/)。

示例代码,它不起作用:

[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);
}

编辑:将来自 Simon 的链接博客文章用于 stub 类。

[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);
}

最佳答案

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

最好的方法是为 HttpContext(或 HttpContextBase)使用模拟或 stub 并调用 RouteCollection 的 GetRouteData(HttpContextBase) 方法并检查路由数据。

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

编辑:您无法从 RouteData 本身获取 Controller 实例。然而,RouteData 应该给你足够的信息来知道哪个 Controller 将被实例化。例如,如果您在 MyProject.Controllers.HomeController 处有一个 Controller ,其操作为 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);

关于c# - MVC4 中的单元测试路由/ Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17286811/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com