Reputation: 2813
My application is an ASP.NET Core 1.0 Web API.
How do I test a controller which is decorated with the Authorize
attribute?
For example, with this controller and test method:
[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. I am 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?
Upvotes: 8
Views: 4404
Reputation: 77846
Well, you are not actually invoking the controller. Rather, you are running a mock test and thus nothing is happening in the conventional way like the 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 because, in your unit test method, no authentication / authorization will take place. You will setup mock and call the controller action method like any other method.
Upvotes: -2
Reputation: 16801
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");
}
Upvotes: 5