4

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.

Ian
  • 321
  • 6
  • 16

1 Answers1

4

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

majita
  • 1,278
  • 14
  • 24