[英]Integration test on controller decorated with [Authorize] attribute
My application is an ASP.NET Core 1.0 Web API.我的应用程序是一个 ASP.NET Core 1.0 Web API。
How do I test a controller which is decorated with the Authorize
attribute?如何测试使用
Authorize
属性修饰的控制器?
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.我实际上是通过
TestServer
对象调用Controller
。
This has already been asked but the accepted answer doesn't work anymore.这已经被问到,但接受的答案不再有效。 Any suggestions how I could "fake" the users' authenticity?
任何建议我如何“伪造”用户的真实性?
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对于 .NET Core,您可以将用户设置为控制器上下文
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");
}
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).
相反,您正在运行模拟测试,因此没有像 ASP.NET 引擎处理您的请求那样以传统方式发生任何事情——请求通过 HTTP 管道(因此是授权模块)传递。
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.因此,在测试时,您应该只关注控制器操作方法的内部逻辑而不是
Authorize
属性,因为在您的单元测试方法中,不会发生身份验证/授权。 You will setup mock and call the controller action method like any other method.您将设置模拟并像任何其他方法一样调用控制器操作方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.