我正在开发一个 ASP.NET MVC 4 项目(.NET 框架 4),我想知道如何正确地对自定义 AuthorizeAttribute 进行单元测试(我使用 NUnit 和 Moq)。
我覆盖了 2 种方法:AuthorizeCore(HttpContextBase httpContext)
和HandleUnauthorizedRequest(AuthorizationContext filterContext)
. 如您所见,这些方法分别期望一个HttpContextBase
和AuthorizationContext
,但我不知道如何模拟这些。
据我所知:
[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