相关文章推荐
玉树临风的枇杷  ·  springtest启动太慢 ...·  2 周前    · 
淡定的油条  ·  Visual Studio 2022 ...·  3 月前    · 
温暖的酱牛肉  ·  三、vue ...·  1 年前    · 
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

Test will fail because it couldn't find HttpContext

So how can I mock HttpContext.Current.User.Identity.Name

I'm using Moq for Mocking

you can initialize your controller with fake context with fake principal as shown below

var fakeHttpContext = new Mock<HttpContextBase>();
var fakeIdentity = new GenericIdentity("User");
var principal = new GenericPrincipal(fakeIdentity, null);
fakeHttpContext.Setup(t => t.User).Returns(principal);
var controllerContext = new Mock<ControllerContext>();
controllerContext.Setup(t => t.HttpContext).Returns(fakeHttpContext.Object);
_requestController = new RequestController();
//Set your controller ControllerContext with fake context
_requestController.ControllerContext = controllerContext.Object;
                Do guys also have a snippet for doing the same thing but uses microsft fakes/test and not any other 3rd party testing framework?
– Randel Ramirez
                Mar 18, 2014 at 15:45

To do it using Microsoft tests only (no 3rd party frameworks), you can do as below:

public class MockHttpContextBase : HttpContextBase
    public override IPrincipal User { get; set; }

And then...

        var userToTest = "User";
        string[] roles = null;
        var fakeIdentity = new GenericIdentity(userToTest);
        var principal = new GenericPrincipal(fakeIdentity, roles);
        var fakeHttpContext = new MockHttpContextBase { User = principal };
        var controllerContext = new ControllerContext
            HttpContext = fakeHttpContext
        // This is the controller that we wish to test:
        _requestController = new RequestController();
        // Now set the controller ControllerContext with fake context
        _requestController.ControllerContext = controllerContext;           
                This solution is working for me in the ASP.Net MVC application when creating a Test Case.
– Saket Yadav
                Oct 13 at 6:17
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.