Mocking with FeatureToggle

I was asked a question on Twitter so I thought I’d write it up here.

When using the FeatureToggle library you may have some some code that behaves differently if a toggle is enabled.

When writing a test, you can create a mock IFeatureToggle and set it up to be enabled (or not) and then assert the result is as expected.

The following code show a simple console app that has an OptionsConsoleWriter.Generate method that uses a toggle to output a printing feature option:

using static System.Console;
using System.Text;
using FeatureToggle.Toggles;
using FeatureToggle.Core;

namespace ConsoleApp1
{
    public class Printing : SimpleFeatureToggle {}

    public class OptionsConsoleWriter
    {
        public string Generate(IFeatureToggle printingToggle)
        {
            var sb = new StringBuilder();

            sb.AppendLine("Options:");
            sb.AppendLine("(e)xport");
            sb.AppendLine("(s)ave");

            if (printingToggle.FeatureEnabled)
            {
                sb.AppendLine("(p)rinting");
            }

            return sb.ToString();
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Printing printingToggle = new Printing();

            string options = new OptionsConsoleWriter().Generate(printingToggle);

            Write(options);            

            ReadLine();
        }
    }
}

To write a couple of simple tests for this method, you can use a mocking framework such as Moq to generate a mocked IFeatureToggle and pass it to the Generate method:

using Xunit;
using Moq;
using FeatureToggle.Core;
using ConsoleApp1;

namespace ClassLibrary1.Tests
{
    public class OptionsConsoleWriterTests
    {
        [Fact]
        public void ShouldGeneratePrintingOption()
        {
            var sut = new OptionsConsoleWriter();

            var mockPrintingToggle = new Mock<IFeatureToggle>();
            mockPrintingToggle.SetupGet(x => x.FeatureEnabled)
                              .Returns(true);

            string options = sut.Generate(mockPrintingToggle.Object);

            Assert.Contains("(p)rinting", options);
        }

        [Fact]
        public void ShouldNotGeneratePrintingOption()
        {
            var sut = new OptionsConsoleWriter();

            var mockPrintingToggle = new Mock<IFeatureToggle>();
            mockPrintingToggle.SetupGet(x => x.FeatureEnabled)
                              .Returns(false);

            string options = sut.Generate(mockPrintingToggle.Object);

            Assert.DoesNotContain("(p)rinting", options);
        }
    }
}

SHARE:

Add comment

Loading