我该如何进行单元测试具有应用[授权]属性的控制器的方法? [英] How do I unit test a controller method that has the [Authorize] attribute applied?

查看:111
本文介绍了我该如何进行单元测试具有应用[授权]属性的控制器的方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我搜索计算器和一派四个几个小时,仍然没有找到我的琐碎的问题的任何解决方案。

I've searched stackoverflow and googled four a couple of hours and still not found any solution for my "trivial" problem.

如果你写单元测试为你过滤 [授权]的ActionResult ,你是怎么解决这个问题假冒该用户进行身份验证?

If you write unit test for your filtered [Authorize] ActionResult, how do you solve the problem to fake that user is authenticated?

我有很多的的ActionResult 的过滤与方法[授权] ,我想测试所有的我的的ActionResult 方法,无论它们是过滤与 [授权] 或没有。

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");
}

截至目前测试甚至不打,因为[授权]过滤器的方法的ActionResult,抛出的异常为: System.NullReferenceException:对象不设置到对象的实例<。 / code>

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.

推荐答案

您需要模拟一个上下文你​​的控制器。尝试使用起订量

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.

这篇关于我该如何进行单元测试具有应用[授权]属性的控制器的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆