2

我在试图弄清楚为什么我的模拟 User.Identity.Name 在我运行测试时返回 null 时遇到了一些困难。我有一种感觉,当我调用我的 controller.ControllerContext 时我可能搞砸了,因为我当时正在设置一些路由,但我不确定如何调整以返回分配对象,就像我在之前的测试中所做的那样。我将 Moq 与 MSTest 一起使用。这是我的测试:

[TestMethod]
    public void Leave_Request_Process_Approved()
    {
        var routes = new RouteCollection();
        routes.MapHttpRoute(name: "myAPI", routeTemplate: "api/myFolder/{controller}/{id}", defaults: new { id = RouteParameter.Optional });
        RouteConfig.RegisterRoutes(routes);

        var controllerContext = new Mock<ControllerContext>();
        var session = new Mock<HttpSessionStateBase>();
        session.SetupGet(s => s["altUser"]).Returns("Mod");
        controllerContext.Setup(p => p.HttpContext.Session).Returns(session.Object);
        controllerContext.Setup(p => p.HttpContext.User.Identity.Name).Returns("User");
        controllerContext.Setup(p => p.HttpContext.Request.UserHostAddress).Returns("127.0.0.1");

        var request = new Mock<HttpRequestBase>();
        request.Setup(x => x.ApplicationPath).Returns("/");
        request.Setup(x => x.Url).Returns(new Uri("http://temp-removed"));
        request.Setup(x => x.ServerVariables).Returns(new System.Collections.Specialized.NameValueCollection());

        var context = new Mock<HttpContextBase>();
        context.SetupGet(x => x.Request).Returns(request.Object);

        var response = new Mock<HttpResponseBase>();
        response.Setup(x => x.ApplyAppPathModifier(It.IsAny<string>())).Returns<string>(x => x);
        context.Setup(x => x.Response).Returns(response.Object);

        var controller = new myController();
        controller.ControllerContext = new ControllerContext(context.Object, new RouteData(), controller);
        controller.Url = new UrlHelper(new RequestContext(context.Object, new RouteData()), routes);

        Assert.IsNotNull(controller.Process(5058, "A", ""));

    }

对于我过去构建的测试,我通常有我的控制器.ControllerContext:

controller.ControllerContext = controllerContext.Object;

我试图查看是否有任何我可以使用的 controllerContext.Setup 选项或 context.Setup 选项,但 Intellisense 没有为我提供任何我可以看到能够替换我在路由信息中调用的位置的选项。

4

1 回答 1

0

而不是ControllerContext模拟 ,您应该能够为 设置一个模拟HttpContextBase.User

context.SetupGet(c => c.User.Identity.Name).Returns("user");

然后将模拟的 Http 上下文传递给ControllerContextctor。

于 2013-03-30T12:12:07.433 回答