Sitecore + TDD: test protected method

The current blog post is a continuation of blogs series about TDD.

This one is about the testing of protected methods. E.g. if you implement custom field type you have to create a class which inherited from Sitecore.Web.UI.HtmlControls.Control one and also implement IContentField interface. The appearance of your custom type field in Content Editor is made by DoRender method which comes from WebControl abstract class.

namespace ExampleOfProtectedMethodTesting
{
    using Sitecore.Diagnostics;
    using Sitecore.Shell.Applications.ContentEditor;
    using System.Web.UI;

    public class CustomField : Sitecore.Web.UI.HtmlControls.Control, IContentField
    {
        public string GetValue() { return this.Value; }

        public void SetValue(string value) { this.Value = value; }

        protected override void DoRender(HtmlTextWriter output)
        {
            Assert.ArgumentNotNull(output, "output");

            output.Write("Hello from CustomField");
        }
    }
}

Using the code above in Content Editor you’ll see such view of the custom field:
custom-field-view

The question is how we can test protected DoRender method. Below code shows that:

namespace CustomFieldTests
{
    using ExampleOfProtectedMethodTesting;
    using FluentAssertions;
    using NUnit.Framework;
    using System.IO;
    using System.Web.UI;

    public class CustomFieldTests
    {
        [TestCase]
        public void DoRender_ShouldFillOutput()
        {
            // arrange
            var customField = new FakeCustomField();
            var output = new HtmlTextWriter(new StringWriter());

            // assert
            output.InnerWriter.ToString().Should().BeEmpty();

            // act
            customField.FakeDoRender(output);

            // assert
            output.InnerWriter.ToString().Should().Be("Hello from CustomField");
        }

        class FakeCustomField : CustomField
        {
            public void FakeDoRender(HtmlTextWriter output)
            {
                base.DoRender(output);
            }
        }
    }
}

As you see the trick is to create a class which is inherited from CustomField one, in example above it is FakeCustomField and create public FakeDoRender method which calls base DoRender.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s