【问题标题】:How to create a unit test that tests that a page requires authorization in mvc5如何创建一个单元测试来测试页面在 mvc5 中需要授权
【发布时间】:2014-02-07 20:30:07
【问题描述】:
我正在尝试研究如何编写一个单元测试来测试控制器授权是否有效。 IE 未登录的用户无法访问该页面。有人知道该怎么做吗?我很难找到示例。
类似这样的东西(伪代码)
[TestMethod]
public void Get_Auth_Page()
{
be_a_user_thats_not_logged_in = true;
// Arrange
MyController controller = new MyController();
// Act
var result = controller.Index();
// Assert
if(result.httpstatus == 403)
Assert.True();
}
【问题讨论】:
标签:
asp.net-mvc
unit-testing
tdd
asp.net-mvc-5
【解决方案1】:
如果你只是简单地用[Authorize] 装饰你的动作方法,你可以只做一个断言属性存在的测试:
[TestMethod]
public void Index_action_requires_authentication()
{
// If Index is overloaded, you might need to filter by argument list
MethodInfo indexMethod = typeof(MyController).GetMethod("Index");
bool requiresAuthentication =
Attribute.IsDefined(indexMethod, typeof(AuthorizeAttribute));
Assert.IsTrue(requiresAuthentication);
}
显然,您没有在此处测试 Authorize 实现,但它确实可以记录并防止开发人员意外删除它。
如果您正在运行自定义代码,那么您可能会返回 HttpStatusCodeResult,因此您可以检查一下:
public void Index_action_requires_authentication()
{
ActionResult result = new MyController().Index();
HttpStatusCodeResult statusCodeResult = result as HttpStatusCodeResult;
Assert.IsNotNull(statusCodeResult);
Assert.AreEqual(403, statusCodeResult.StatusCode);
}
如果您手动写入 HttpResponse(Response.StatusCode 或 Response.Headers),那么您需要像其他人描述的那样模拟 HttpContextBase。