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

后端 未结 8 635
醉梦人生
醉梦人生 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()
       {
       }
    }
    

提交回复
热议问题