Testing controller Action that uses User.Identity.Name

后端 未结 2 791
深忆病人
深忆病人 2020-12-13 04:06

I have an action that relies on User.Identity.Name to get the username of the current user to get a list of his orders:

public ActionResult XLineas()
    {
          


        
相关标签:
2条回答
  • 2020-12-13 04:36

    A better way of doing this would be to pass a string argument userName (or an IPrincipal argument user, if you need more information than just the name) to the ActionMethod, which you "inject" in a normal request using an ActionFilterAttribute. When you test it, you just supply your own mock object, as the action filter's code will not run (in most cases - there are ways to, if you specifically want to...)

    Kazi Manzur Rashid describes this in detail under point 7 in an excellent blog post.

    0 讨论(0)
  • 2020-12-13 04:52

    You can use this code

    public SomeController CreateControllerForUser(string userName) 
    {
        var mock = new Mock<ControllerContext>();
        mock.SetupGet(p => p.HttpContext.User.Identity.Name).Returns(userName);
        mock.SetupGet(p => p.HttpContext.Request.IsAuthenticated).Returns(true);
    
        var controller = new SomeController();
        controller.ControllerContext = mock.Object;
    
        return controller;
    }
    

    It uses Moq mocking framework, but sure you can use anything you like.

    0 讨论(0)
提交回复
热议问题