如何在mvc5中创建一个单元测试来测试页面是否需要授权



我正在努力研究如何编写一个单元测试,以测试控制器授权是否有效。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();
}

如果你只是用[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

最新更新