Integration test Controller decorated with [Authorize] attribute

Integration test Controller decorated with [Authorize] attribute

My application is an ASP.NET Core 1.0 Web API.
As the title says: How do I test a controller which is decorated with the Authorize attribute? 
For example with this controller and testmethod:
  [TestMethod]
  public void GetSomeDataTest()
  {
     var controller = new MyController();
     Assert.AreEqual(controller.GetSomeData(), "Test");
  }

  [Authorize]
  public ActionResult GetSomeData()
  {
     return this.Content("Test");
  }

This is just an example code to make it possible for you guys to answer. Iam actually invoking the Controller via a TestServer object.
This has already been asked but the accepted answer doesn't work anymore.
Any suggestions how I could "fake" the users authenticity?
Thank you

Solutions/Answers:

Answer 1:

You could set a claim principle to the current thread

[TestInitialize]
public void Initialize()
{
    var claims = new List<Claim>() 
    { 
        new Claim(ClaimTypes.Name, "UserName"),
        new Claim(ClaimTypes.Role, "Admin")
    };
    var identity = new ClaimsIdentity(claims, "TestAuth");
    var claimsPrincipal = new ClaimsPrincipal(identity);
    Thread.CurrentPrincipal = claimsPrincipal;
}

Update

For .Net Core you could set the user to the controller context

private MyController _ctrl;

[TestInitialize]
public void Initialize()
{
    var user = new ClaimsPrincipal(new ClaimsIdentity(new Claim[]
    {
         new Claim(ClaimTypes.Name, "UserName"),
         new Claim(ClaimTypes.Role, "Admin")
    }));

    _ctrl = new MyController();
    _ctrl.ControllerContext = new ControllerContext()
    {
        HttpContext = new DefaultHttpContext() { User = user }
    };
}

[TestMethod]
public void GetSomeDataTest()
{
    Assert.AreEqual(_ctrl.GetSomeData(), "Test");
}

Answer 2:

Well you are not actually invoking the controller, rather you are running a mock test and thus nothing is happening in conventional way like ASP.NET engine handling your request -> request passing through HTTP pipeline (thus authorization module).

So while testing, you should only concentrate on the internal logic of the controller action method instead of that Authorize attribute cause in your unit test method no authenticatrion / authorization will take place. You will setup mock and call the controller action method likewise any other method.

Our Awesome Free Tools

References