代码之家  ›  专栏  ›  技术社区  ›  MSI

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

  •  5
  • MSI  · 技术社区  · 16 年前

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

    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() { }
        }
    
    2 回复  |  直到 16 年前
        1
  •  2
  •   Jakob Gade    16 年前

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