模拟Request.Url

时间:2017-01-27 08:07:36

标签: .net asp.net-mvc nunit

我的控制器使用以下行将URL分配给会话

this.Session["MyUrl"] = Request.Url.ToString();

在单元测试项目方面我设置了这样的控制器

var fakeHttpContext = new Mock<HttpContextBase>();
var controllerContext = new Mock<ControllerContext>();
controllerContext.Setup(t => t.HttpContext).Returns(fakeHttpContext.Object);
this.controller.ControllerContext = controllerContext.Object;            
controllerContext.SetupGet(x => x.HttpContext.Request.Url).Returns(new Uri("/Home/Details", UriKind.Relative));

在最后一行我试图设置Request.Url以传递我期望在控制器端的值。

我在Request.Url上获得的结果是'/Home/Details'

我是否需要在请求中模拟整个Url对象才能使其生效?

更新: 我在httpcontext setup

中设置了会话对象
fakeHttpContext.Setup(x => x.Session["MyUrl"]).Returns("/Home/Details");

但仍然遇到同样的问题。

1 个答案:

答案 0 :(得分:3)

您似乎没有正确地模拟ControllerContext。试试这个:

// arrange
var controller = new HomeController();
var context = new Mock<HttpContextBase>();
var session = new Mock<HttpSessionStateBase>();
context.Setup(x => x.Request.Url).Returns(new Uri("/Home/Details", UriKind.Relative));
context.Setup(x => x.Session).Returns(session.Object);
var requestContext = new RequestContext(context.Object, new RouteData());
controller.ControllerContext = new ControllerContext(requestContext, controller);

// act
var actual = controller.Index();

// assert
session.VerifySet(x => x["MyUrl"] = "/Home/Details");
...