Mvc controller单元测试 Mock Url对象

时间:2023-12-25 11:16:07

被测试Action 包含有Url对象的代码:

                 data = new data
{
title = ds.Name,
icon = "folder",
attr = new { id = "root", href = Url.Action("ManageDSByLevel", new { levelid = firstlevel.ID }), name = ds.Name },
},

在进行单元测试时需要Mock Url对象,以顺利通过测试,以下为Mock Url 代码:

             var dsController = new DealerStructureController(dsService.Object, pcService.Object);
dsController.Mapper = mapper.Object; 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.Setup(ctx => ctx.Request).Returns(request.Object);
context.Setup(ctx => ctx.Response).Returns(response.Object);
//context.Setup(ctx => ctx.Session).Returns(session.Object);
//context.Setup(ctx => ctx.Server).Returns(server.Object); //request.SetupGet(x => x.ApplicationPath).Returns("/");
//request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute));
//request.SetupGet(x => x.ServerVariables).Returns(new NameValueCollection()); //response.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(x => x); //context.SetupGet(x => x.Request).Returns(request.Object);
//context.SetupGet(x => x.Response).Returns(response.Object); var routes = new RouteCollection();
MvcApplication.RegisterRoutes(routes);
var helper = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);
dsController.Url = helper;

在这段代码中 Url对象使用了Url.Action方法,所以在mock Url 时只是简单的模拟,如果代码中使用了Urlde其他方法,可把注解的代码恢复使用。