如何对应用了 [Authorize] 属性的控制器方法进行单元测试? [英] How do I unit test a controller method that has the [Authorize] attribute applied?
问题描述
我搜索了 stackoverflow 并用了几个小时的谷歌搜索了四个,但仍然没有找到任何解决我的琐碎"问题的方法.
I've searched stackoverflow and googled four a couple of hours and still not found any solution for my "trivial" problem.
如果您为过滤后的 [Authorize] ActionResult
编写单元测试,您如何解决假冒该用户已通过身份验证的问题?
If you write unit test for your filtered [Authorize] ActionResult
, how do you solve the problem to fake that user is authenticated?
我有很多用 [Authorize]
过滤的 ActionResult
方法,我想测试我所有的 ActionResult
方法,不管是否它们是否使用 [Authorize]
进行过滤.
I have a lot of ActionResult
methods that are filtered with [Authorize]
and I want to test all of my ActionResult
methods regardless if they are filtered with [Authorize]
or not.
我的意思的一个简单例子:
A simple example of what i mean:
[TestMethod]
public void Create_Get_ReturnsView()
{
// Arrange
var controller = new UserController();
// Act
var result = controller.Create();
// Assert
Assert.IsNotNull(result as ViewResult);
}
[Authorize]
public ActionResult Create()
{
return View("Create");
}
截至目前,由于 [Authorize] 过滤器,测试甚至没有命中 ActionResult 方法,抛出的异常是:System.NullReferenceException:未将对象引用设置为对象的实例.
As of now the tests don't even hit the ActionResult method because of the [Authorize] filter, exception thrown is: System.NullReferenceException: Object reference not set to an instance of an object.
推荐答案
您需要模拟控制器的上下文.尝试使用 Moq
You need to mock a context for your controller. Try using Moq
您的安排将如下所示:
var controller = new UserController();
var mock = new Mock<ControllerContext>();
mock.SetupGet(x => x.HttpContext.User.Identity.Name).Returns("SOMEUSER");
mock.SetupGet(x => x.HttpContext.Request.IsAuthenticated).Returns(true);
controller.ControllerContext = mock.Object;
然后你应该能够做你的行动 &断言.
You should be able to then do your Act & Assert.
如果您还没有,我强烈建议您浏览 NerdDinner 作为MVC 站点示例.
If you haven't already, I would highly recommend looking through NerdDinner as an example MVC site.
这篇关于如何对应用了 [Authorize] 属性的控制器方法进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!