Reputation: 447
I am pretty new to creating unit test for function, and are currently given the task to create some unit test for this 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();
}
}
}
The process function is pretty neat, nicely seperated into if statements, which can be individually tested, but the problem here is that the function doesn't return anything so there is nothing to catch...
How do I go by creating unit test for this kind of functions?
Upvotes: 2
Views: 1058
Reputation: 3676
You would need to create a mock HTTPContext and inject it into the method for the test. (You probably need to mock quite a few other objects too, since the method has several dependencies.)
Then, after the method has run, assert that the the response in the context is as you want it.
See details here: Mock HttpContext.Current in Test Init Method
Upvotes: 2