首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何对依赖于HttpContext.Current和Sitecore.Context的类进行单元测试?

如何对依赖于HttpContext.Current和Sitecore.Context的类进行单元测试?
EN

Stack Overflow用户
提问于 2018-11-13 13:53:17
回答 1查看 826关注 0票数 2

我对于为函数创建单元测试非常陌生,目前被赋予了为该类创建一些单元测试的任务。

代码语言:javascript
运行
复制
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语句,这些语句可以单独测试,但这里的问题是该函数不返回任何内容,因此没有什么要捕获的。

如何为这类函数创建单元测试?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-11-13 14:00:55

您需要创建一个模拟HTTPContext并将其插入到测试的方法中。(您可能还需要模拟许多其他对象,因为该方法有几个依赖项。)

然后,在方法运行之后,断言上下文中的响应是您想要的。

请参阅这里的详细信息:Mock HttpContext.Current in Test Init Method

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/53282567

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档