11

我正在开发一个 ASP.NET MVC 4 项目(.NET 框架 4),我想知道如何正确地对自定义 AuthorizeAttribute 进行单元测试(我使用 NUnit 和 Moq)。

我覆盖了 2 种方法:AuthorizeCore(HttpContextBase httpContext)HandleUnauthorizedRequest(AuthorizationContext filterContext). 如您所见,这些方法分别期望一个HttpContextBaseAuthorizationContext,但我不知道如何模拟这些。

据我所知:

[Test]
public void HandleUnauthorizedRequest_UnexistingMaster_RedirectsToCommonNoMaster()
{
    // Arrange
    var httpContext = new Mock<HttpContextBase>();
    var winIdentity = new Mock<IIdentity>();
    winIdentity.Setup(i => i.IsAuthenticated).Returns(() => true);
    winIdentity.Setup(i => i.Name).Returns(() => "WHEEEE");
    httpContext.SetupGet(c => c.User).Returns(() => new ImdPrincipal(winIdentity.Object)); // This is my implementation of IIdentity
    var requestBase = new Mock<HttpRequestBase>();
    var headers = new NameValueCollection
        {
           {"Special-Header-Name", "false"}
        };
    requestBase.Setup(x => x.Headers).Returns(headers);
    requestBase.Setup(x => x.HttpMethod).Returns("GET");
    requestBase.Setup(x => x.Url).Returns(new Uri("http://localhost/"));
    requestBase.Setup(x => x.RawUrl).Returns("~/Maintenance/UnExistingMaster");
    requestBase.Setup(x => x.AppRelativeCurrentExecutionFilePath).Returns(() => "~/Maintenance/UnExistingMaster");
    requestBase.Setup(x => x.IsAuthenticated).Returns(() => true);
    httpContext.Setup(x => x.Request).Returns(requestBase.Object);
    var controller = new Mock<ControllerBase>();
    var actionDescriptor = new Mock<ActionDescriptor>();
    var controllerContext = new ControllerContext(httpContext.Object, new RouteData(), controller.Object);

    // Act
    var masterAttr = new ImdMasterAuthorizeAttribute();
    var filterContext = new AuthorizationContext(controllerContext, actionDescriptor.Object);
    masterAttr.OnAuthorization(filterContext);

    // Assert
    Assert.AreEqual("", filterContext.HttpContext.Response);
}

上线:masterAttr.OnAuthorization(filterContext);aNullReferenceException被抛出。我认为它与我们尚未模拟的上下文中的值有关。

任何帮助是极大的赞赏。

提前致谢。

此致, Yanik Ceulemans

4

1 回答 1

8

如果没有属性代码,只能猜测。但要开始调查,您可以使用MockBehavior.Strict. 这样,当在没有先前设置的情况下调用模拟上的方法或属性时,Moq 将引发异常。异常将具有方法/属性的名称:

var httpContext = new Mock<HttpContextBase>(MockBehavior.Strict);
于 2013-09-17T00:07:20.773 回答