Writing Unit Test for methods that use User.Identity.Name in ASP.NET Web API

后端 未结 8 636
醉梦人生
醉梦人生 2020-12-29 18:33

I am writing test cases using the Unit Test for ASP.NET Web API.

Now I have an action which makes a call to some method I have defined in the service layer, where I

8条回答
  •  梦谈多话
    2020-12-29 19:07

    Here i found the solution for another way that how to set the user identity name for the controller level testing from the test method.

    public static void SetUserIdentityName(string userId)
            {
                IPrincipal principal = null;
                principal = new GenericPrincipal(new GenericIdentity(userId), 
                new string[0]);
                Thread.CurrentPrincipal = principal;
                if (HttpContext.Current != null)
                {
                    HttpContext.Current.User = principal;
                }
            }
    

提交回复
热议问题