I am having a bit of a rough time trying to figure out why my mocked User.Identity.Name is returning null when I run my test. I have a feeling that I may have screwed up when I called my controller.ControllerContext because I am setting up some routes at that point, but I am unsure how to adjust to go back to assigning an object as I have done on previous tests. I'm using Moq with MSTest. Here is my test:
[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", ""));
}
With tests I have built in the past, I normally have for my controller.ControllerContext:
controller.ControllerContext = controllerContext.Object;
I have tried to see if there is any controllerContext.Setup options or context.Setup options I could use, but Intellisense doesn't provide me with any options that I can see to be able to replace where I call in my route information.
Instead of mocking the ControllerContext
, you should be able to just set up a mock for the HttpContextBase.User
:
context.SetupGet(c => c.User.Identity.Name).Returns("user");
And then pass that mocked Http context to the ControllerContext
ctor.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.