我有以下要进行单元测试的 HttpModule。问题是我不允许更改访问修饰符/静态,因为它们需要保持原样。我想知道测试以下模块的最佳方法是什么。我在测试东西方面还是很新的,主要是寻找有关测试策略和一般测试 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() { }
}
最佳答案
对于仍在寻找的其他人,这篇文章解释了一种方法
原页面已被删除,您可以在这里查看文章:
https://web.archive.org/web/20151219105430/http://weblogs.asp.net/rashid/unit-testable-httpmodule-and-httphandler
关于ASP.NET + NUnit : Good unit testing strategy for HttpModule using . NET 4,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3648610/