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
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()
{
}
}
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;