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

后端 未结 8 574
醉梦人生
醉梦人生 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:22

    If you have lots of Controllers to Test then I Would Suggest to create a base class and in the constructor create a GenericIdentity & GenericPrincipal and set Thread.CurrentPrincipal

    GenericPrincipal principal = new GenericPrincipal(new 
        GenericIdentity("UserName"),null); Thread.CurrentPrincipal = principal; 
    

    Then Inherit that class .. So that way every Unit Test class will have Principle Object Set

    [TestClass]
    public class BaseUnitTest
    {
        public BaseUnitTest()
        {
          GenericPrincipal principal = new GenericPrincipal(new GenericIdentity("UserName"),null);   
          Thread.CurrentPrincipal = principal;
        }
    }
    
    
    [TestClass]
    public class AdminUnitTest : BaseUnitTest
    {
       [TestMethod]
       public void Admin_Application_GetAppliction()
       {
       }
    }
    
    0 讨论(0)
  • 2020-12-29 19:24

    This is my solution.

    var claims = new List<Claim>
    {
        new Claim(ClaimTypes.Name, "Nikita"),
        new Claim(ClaimTypes.NameIdentifier, "1")
    };
    
    var identity = new ClaimsIdentity(claims);
    IPrincipal user = new ClaimsPrincipal(identity);
    
    controller.User = user;
    
    0 讨论(0)
提交回复
热议问题