Sitecore + TDD: assertions

All we know Assert static class from Sitecore.Diagnostics namespace and its methods which help us to be sure that methods get proper parameters.

E.g. if you explore Sitecore.Kernel and in particular code of pipelines you see something like that:

namespace Sitecore.Pipelines.SomePipeline
{
	public class DoSomething
	{
		public void Process(SomeArgs args)
		{
			Assert.ArgumentNotNull(args, "args");
			...
		}
	}
}

In the example below, I’ll show how we can test assertion using FluentAssertions.

namespace ExampleOfAssertionTesting
{
    using Sitecore.Diagnostics;

    public class AssertionExample
    {
        public void DoSomething(SomeData someData)
        {
            Assert.ArgumentNotNull(someData, "someData");
            Assert.ArgumentNotNullOrEmpty(someData.SomeString, "someData.SomeString");

            // TODO
        }
    }

    public class SomeData
    {
        public string SomeString { get; set; }
    }
}

Tests:

namespace AssertionTests
{
    using ExampleOfAssertionTesting;
    using FluentAssertions;
    using NUnit.Framework;
    using System;

    public class AssertionExampleTests
    {
        [TestCase]
        public void DoSomething_ShouldThrowArgumentNullException_WhenSomeDataIsNull()
        {
            // arrange
            var assertionExample = new AssertionExample();

            // act
            Action action = () => assertionExample.DoSomething(null);

            // assert
            action.ShouldThrowExactly<ArgumentNullException>();
        }

        [TestCase]
        public void DoSomething_ShouldThrowArgumentException_WhenSomeStringIsEmpty()
        {
            // arrange
            var assertionExample = new AssertionExample();
            var someData = new SomeData { SomeString = string.Empty };

            // act
            Action action = () => assertionExample.DoSomething(someData);

            // assert
            action.ShouldThrowExactly<ArgumentException>();

            try
            {
                action();
            }
            catch (ArgumentException ex)
            {
                ex.Message.Should().Contain("someData.SomeString");
            }
        }
    }
}

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