Integration test on controller decorated with [Authorize] attribute
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;
}
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");
}