ASP.NET + NUnit:使用.NET 4的HttpModule的良好单元测试策略

MSI*_*MSI 6 asp.net nunit c#-4.0

我有以下HttpModule,我想进行单元测试.问题是我不允许更改访问修饰符/ static,因为它们需要保持原样.我想知道测试以下模块的最佳方法是什么.我在测试内容方面还很陌生,主要是寻找有关测试策略和一般测试HttpModules的技巧.仅仅是为了澄清,我只是试图获取每个请求的URL(仅限.aspx页面)并检查所请求的URL是否具有权限(对于我们的Intranet中的特定用户).到目前为止,感觉我无法真正测试这个模块(从生产的角度来看).

public class PageAccessPermissionCheckerModule : IHttpModule
    {
        [Inject]
        public IIntranetSitemapProvider SitemapProvider { get; set; }
        [Inject]
        public IIntranetSitemapPermissionProvider PermissionProvider { get; set; }

        public void Init(HttpApplication context)
        {
            context.PreRequestHandlerExecute += ValidatePage;
        }

        private void EnsureInjected()
        {
            if (PermissionProvider == null)
                KernelContainer.Inject(this);
        }

        private void ValidatePage(object sender, EventArgs e)
        {
            EnsureInjected();

            var context = HttpContext.Current ?? ((HttpApplication)sender).Context;

            var pageExtension = VirtualPathUtility.GetExtension(context.Request.Url.AbsolutePath);

            if (context.Session == null || pageExtension != ".aspx") return;

            if (!UserHasPermission(context))
            {
                KernelContainer.Get<UrlProvider>().RedirectToPageDenied("Access denied: " + context.Request.Url);
            }
        }

        private bool UserHasPermission(HttpContext context)
        {
            var permissionCode = FindPermissionCode(SitemapProvider.GetNodes(), context.Request.Url.PathAndQuery);

            return PermissionProvider.UserHasPermission(permissionCode);
        }

        private static string FindPermissionCode(IEnumerable<SitemapNode> nodes, string requestedUrl)
        {
            var matchingNode = nodes.FirstOrDefault(x => ComparePaths(x.SiteURL, requestedUrl));

            if (matchingNode != null)
                return matchingNode.PermissionCode;

            foreach(var node in nodes)
            {
                var code = FindPermissionCode(node.ChildNodes, requestedUrl);
                if (!string.IsNullOrEmpty(code))
                    return code;
            }

            return null;
        }  
        public void Dispose() { }
    }
Run Code Online (Sandbox Code Playgroud)

Rig*_*iga 7

对于仍在寻找的其他人,这篇文章解释了一种方法

原始页面已删除,您可以访问以下文章:https://web.archive.org/web/20151219105430/http: //weblogs.asp.net/rashid/unit-testable-httpmodule-and-httphandler


Jak*_*ade 2

测试 HttpHandler 可能很棘手。我建议您创建第二个库并将您想要测试的功能放在那里。这也能让你更好地分离关注点。