如何对依赖于 HttpContext.Current 和 Sitecore.Context 的 class 进行单元测试?
How do I unit test a class that depends on HttpContext.Current and Sitecore.Context?
我对为函数创建单元测试还很陌生,目前我的任务是为此 class 创建一些单元测试。
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();
}
}
}
process函数很简洁,很好地分成if语句,可以单独测试,但这里的问题是
该函数没有 return 任何东西,所以没有什么可捕捉的...
如何为此类功能创建单元测试?
您需要创建一个模拟 HTTPContext 并将其注入到测试方法中。 (您可能还需要模拟很多其他对象,因为该方法有多个依赖项。)
然后,在方法 运行 之后,断言上下文中的响应是您想要的。
在此处查看详细信息:
我对为函数创建单元测试还很陌生,目前我的任务是为此 class 创建一些单元测试。
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();
}
}
}
process函数很简洁,很好地分成if语句,可以单独测试,但这里的问题是 该函数没有 return 任何东西,所以没有什么可捕捉的...
如何为此类功能创建单元测试?
您需要创建一个模拟 HTTPContext 并将其注入到测试方法中。 (您可能还需要模拟很多其他对象,因为该方法有多个依赖项。)
然后,在方法 运行 之后,断言上下文中的响应是您想要的。
在此处查看详细信息: