被测试Action 包含有Url对象的代码:
1 data = new data 2 { 3 title = ds.Name, 4 icon = "folder", 5 attr = new { id = "root", href = Url.Action("ManageDSByLevel", new { levelid = firstlevel.ID }), name = ds.Name }, 6 },
在进行单元测试时需要Mock Url对象,以顺利通过测试,以下为Mock Url 代码:
1 var dsController = new DealerStructureController(dsService.Object, pcService.Object); 2 dsController.Mapper = mapper.Object; 3 4 var context = new Mock<HttpContextBase>(); 5 var request = new Mock<HttpRequestBase>(); 6 var response = new Mock<HttpResponseBase>(); 7 //var session = new Mock<HttpSessionStateBase>(); 8 //var server = new Mock<HttpServerUtilityBase>(); 9 10 context.Setup(ctx => ctx.Request).Returns(request.Object); 11 context.Setup(ctx => ctx.Response).Returns(response.Object); 12 //context.Setup(ctx => ctx.Session).Returns(session.Object); 13 //context.Setup(ctx => ctx.Server).Returns(server.Object); 14 15 //request.SetupGet(x => x.ApplicationPath).Returns("/"); 16 //request.SetupGet(x => x.Url).Returns(new Uri("http://localhost/a", UriKind.Absolute)); 17 //request.SetupGet(x => x.ServerVariables).Returns(new NameValueCollection()); 18 19 //response.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(x => x); 20 21 //context.SetupGet(x => x.Request).Returns(request.Object); 22 //context.SetupGet(x => x.Response).Returns(response.Object); 23 24 var routes = new RouteCollection(); 25 MvcApplication.RegisterRoutes(routes); 26 var helper = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes); 27 dsController.Url = helper;
在这段代码中 Url对象使用了Url.Action方法,所以在mock Url 时只是简单的模拟,如果代码中使用了Urlde其他方法,可把注解的代码恢复使用。