1

I am attempting to mock IPrinciple (as i had a controller action which used User.Identity.Name, for which I would like to write unit test for) in my Unit Test(using .net 5 preview). Refering to answer in this question, I have the following in my Unit Test.

var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
    new Claim(ClaimTypes.Name, userName),
               
}, "mock"));
userController.ControllerContext = new ControllerContext()
{
                 
    HttpContext = new DefaultHttpContext() { User = user }
};

However, I recieve following error.

Reference to type 'HttpContextBase' claims it is defined in 'System.Web', but it could not be found

I saw a similiar question here, but the answer directs to change the target version. I was wondering if there was a way out without changing target version.

Anu Viswan
  • 17,797
  • 2
  • 22
  • 51

1 Answers1

1

Finally managed to solve it, leaving the answer here for anyone who might face a similar situation.

Instead of replacing the ControllerContext completely, I replaced ControllerContext.HttpContext

var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
{
    new Claim(ClaimTypes.Name, userName),
               
}, "mock"));
userController.ControllerContext.HttpContext = new DefaultHttpContext() { User = user };

This ensured the Controller could receive UserName with

var userName = User.Identity.Name;
Anu Viswan
  • 17,797
  • 2
  • 22
  • 51