Working in asp.net core, there are several controllers which has claims. The sample code is like this.
[HttpGet, Route("GetCustomerList")]
public ActionResult<GenericResponse> Get()
{
var claims = User as ClaimsPrincipal;
string username = claims.Claims.Where(c => c.Type == "UserName").Select(x => x.Value).FirstOrDefault();
string roleid = claims.Claims.Where(c => c.Type == "RoleId").Select(x => x.Value).FirstOrDefault();
........
........
}
How should I handle this claims while controller testing? I have tried the solution given How to add claims in a mock ClaimsPrincipal i.e. first solution. However, in my controller while debugging gives User a null and it stops.
The User you are trying to access in your controller is found on the HttpContext so you can create a DefaultHttpContext for the controller under test and link a ClaimsPrincipal to this DefaultHttpContext as per the example below:
var fakeClaims = new List<Claim>()
{
new Claim(ClaimTypes.Name, "name"),
new Claim("RoleId", "1"),
new Claim("UserName", "John")
};
var fakeIdentity = new ClaimsIdentity(fakeClaims, "TestAuthType");
var fakeClaimsPrincipal = new ClaimsPrincipal(fakeIdentity);
ControllerToTest controller = new ControllerToTest();
ControllerToTest.ControllerContext.HttpContext = new DefaultHttpContext
{
User = fakeClaimsPrincipal
};
ControllerToTest.Get();
You can also mock the HttpContext as per this example
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With