我对于为函数创建单元测试非常陌生,目前被赋予了为该类创建一些单元测试的任务。
namespace Sandbox.Processors
{
using Sitecore.Data.Items;
using Sitecore.Pipelines.HttpRequest;
using System;
using System.Web;
public class RobotsTxtProcessor : HttpRequestProcessor
{
public override void Process(HttpRequestArgs args)
{
HttpContext context = HttpContext.Current;
if (context == null)
{
return;
}
string requestUrl = context.Request.Url.ToString();
if (string.IsNullOrEmpty(requestUrl) || !requestUrl.ToLower().EndsWith("robots.txt"))
{
return;
}
string robotsTxtContent = @"User-agent: *"
+ Environment.NewLine +
"Disallow: /sitecore";
if (Sitecore.Context.Site != null && Sitecore.Context.Database != null)
{
Item homeNode = Sitecore.Context.Database.GetItem(Sitecore.Context.Site.StartPath);
if (homeNode != null)
{
if ((homeNode.Fields["Site Robots TXT"] != null) &&
(!string.IsNullOrEmpty(homeNode.Fields["Site Robots TXT"].Value)))
{
robotsTxtContent = homeNode.Fields["Site Robots TXT"].Value;
}
}
}
context.Response.ContentType = "text/plain";
context.Response.Write(robotsTxtContent);
context.Response.End();
}
}
}流程函数非常整洁,很好地分离为if语句,这些语句可以单独测试,但这里的问题是该函数不返回任何内容,因此没有什么要捕获的。
如何为这类函数创建单元测试?
发布于 2018-11-13 14:00:55
您需要创建一个模拟HTTPContext并将其插入到测试的方法中。(您可能还需要模拟许多其他对象,因为该方法有几个依赖项。)
然后,在方法运行之后,断言上下文中的响应是您想要的。
请参阅这里的详细信息:Mock HttpContext.Current in Test Init Method
https://stackoverflow.com/questions/53282567
复制相似问题