Pimp Up Your Unit Test Assertions

In this post I’m going to show you how you can write your unit test assertions to read more fluently and allow you to be more productive.

The Plain Jane Unit Test Assertion

[Test]
public void The_Plain_Jane_Assertion()
{
    const string firstString = "Hello World";
    const string secondString = "Hello World";

    const int smallNumber = 1;
    const int bigNumber = 500;

    // Are Equal
    Assert.AreEqual(firstString, secondString);

    // Greater Than
    Assert.Greater(bigNumber,smallNumber);

    // Less Than
    Assert.Less(smallNumber,bigNumber);
}

This is what most developers will start off using. No problem with the equals assertion it easy enough to read and use.

However when using the greater or less than assertions, it’s not clear if the first argument should be the lower or the higher value as shown in the screen shot below.

NUnit Assert Confusion

This distraction can easily stop your flow.

The More Fluent NUnit Test Assertion

[Test]
public void The_More_Fluent_Nunit_Assertion()
{
    const string firstString = "Hello World";
    const string secondString = "Hello World";

    const int smallNumber = 1;
    const int bigNumber = 500;

    // Are Equal
    Assert.That(firstString, Is.EqualTo(secondString));

    // Greater Than
    Assert.That(bigNumber, Is.GreaterThan(smallNumber));

    // Less Than
    Assert.That(smallNumber, Is.LessThan(bigNumber));
}

The unit test assertions read a lot more fluently, we no longer have to be concerned about the order of arguments.

If you don’t want to use another third party library, this is for you.

The Super Fluent NBehave Spec Assertion

[Test]
public void The_Super_Fluent_NBehave_Spec_Assertion()
{
    const string firstString = "Hello World";
    const string secondString = "Hello World";

    const int smallNumber = 1;
    const int bigNumber = 500;

    // Are Equal
    firstString.ShouldEqual(secondString);

    // Greater Than
    bigNumber.ShouldBeGreaterThan(smallNumber);

    // Less Than
    smallNumber.ShouldBeLessThan(bigNumber);
}

This example uses the NBehave Spec Framework which you can download from the NBehave site. In addition to being very easy to understand, the use of extension methods means there is a lot less noise.

Some developers will be concerned by losing the word ‘Assert’ in the line that does the assertion. If you arrange your tests using the Arrange, Act, Assert pattern this should not be a problem. See the example below.

[Test]
public void The_NBehave_Spec_Assertion_Using_Arrange_Act_Assert()
{
    // Arrange
    const int inputValue = 1;

    // Act
    var result = inputValue + 1;

    // Assert
    result.ShouldBeGreaterThan(inputValue);
}

Ever Thought About Changing How You Name Unit Tests?

In the last couple of months I’ve seen a new convention of how developers are naming their unit test classes.

Traditionally the naming convention most developers use is to append the word ‘Tests’ to the class name as shown below.

public class UserValidation
{
}

[TestFixture]
public class UserValidationTests
{
}

There is absolutely nothing wrong with it, but this can lead to problems because a test class can become unwieldy and difficult to maintain either because it’s too long, testing a lot of different concerns or both.

In some cases it would make more sense to take different approach and adopt an alternative naming convention. Sticking with the example above instead of having tests for validating a user in one class, a new class could be created for each concern. So instead of

using System;
using NUnit.Framework;
using NBehave.Spec.NUnit;

namespace MyApplication.Validation
{
    [TestFixture]
    public class UserValidationTests
    {
        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Short()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsUsernameValid(string.Empty);

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Username_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Username_Is_Valid() { }

        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Short() { }

        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Numbers()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsPasswordValid("123456");

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Alphabetical_Characters() { }

        [Test]
        public void Should_Return_False_When_Password_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Password_Is_Valid() { }
    }
}

we create two test classes

using System;
using NUnit.Framework;
using NBehave.Spec.NUnit;

namespace MyApplication.Validation
{
    [TestFixture]
    public class When_Validating_A_Users_Username
    {
        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Short()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsUsernameValid(string.Empty);

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Username_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Username_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Username_Is_Valid() { }
    }

    [TestFixture]
    public class When_Validating_A_Users_Password
    {
        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Short() { }

        [Test]
        public void Should_Return_False_When_Password_Length_Is_To_Long() { }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Numbers()
        {
            // Arrange
            UserValidation userValidation = new UserValidation();

            // Act
            bool result = userValidation.IsPasswordValid("123456");

            // Assert
            result.ShouldEqual(false);
        }

        [Test]
        public void Should_Return_False_When_Password_Is_Just_Alphabetical_Characters() { }

        [Test]
        public void Should_Return_False_When_Password_Contains_Invalid_Characters() { }

        [Test]
        public void Should_Return_True_When_Password_Is_Valid() { }
    }
}

I think this behavior driven development type naming convention will help focus on the problem you are solving and nothing more. This is very useful when doing test driven development.

When I first saw tests written like this my first thought was how am I going to find the all the tests for User Validation because they are no longer in a single class? If this is a problem for you think about using namespaces, folders or test attributes to organise your tests. Don’t forget if you use tools like ReSharper help you find where a class is being used very easily.

Remember this is about renaming your tests classes and not your methods. So even if you follow the MethodName_StateUnderTest_ExpectedBehavior pattern for test methods this could still work.

Creating the animals game using Asp.Net MVC, jQuery and jQueryUI

A few weeks ago we had some fun creating a demo for a game using the jQuery and jQuery UI libraries in the ‘Having fun with jQuery UI’ blog post.

In this post we will go through how to create the game using ASP.NET MVC, jQuery and jQuery UI.

The screenshot below shows the game running.

Screenshot of Game using Asp.Net MVC, jQuery and jQueryUI

The code used for creating the game in ASP.NET MVC, jQuery and jQuery UI can be downloaded here.

Getting Started

Instead of three animals used in the demo, the game now contains fourteen. I’ve created a repository which returns the animals. To keep things simple there’s no database here, instead the animals are hard coded.

using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;

namespace GameUsingAspNetMVCandJQueryUI.Core.Repository
{
    public class AnimalsRepository : IAnimalsRepository
    {
        public IQueryable<Animal> GetAll()
        {
            return new Animal[]
                       {
                           new Animal(){Name = "Cow"},
                           new Animal(){Name = "Cat"},
                           new Animal(){Name = "Chicken"},
                           new Animal(){Name = "Dog"},
                           new Animal(){Name = "Elephant"},
                           new Animal(){Name = "Giraffe"},
                           new Animal(){Name = "Hippo"},
                           new Animal(){Name = "Lion"},
                           new Animal(){Name = "Monkey"},
                           new Animal(){Name = "Mouse"},
                           new Animal(){Name = "Owl"},
                           new Animal(){Name = "Penguin"},
                           new Animal(){Name = "Pig"},
                           new Animal(){Name = "Sheep"},
                       }
                .AsQueryable();
        }
    }
}

Command Query Separation

One of the features I have added is to ensure a correct answer for the current game could not be the correct answer in the next. As the repository class was responsible for getting animals, having it contain any logic would violate good design principles.

So the logic goes into the service layer which returns a data transfer object for animals and the correct answer.

using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.ExtensionMethods;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using GameUsingAspNetMVCandJQueryUI.Core.Repository;

namespace GameUsingAspNetMVCandJQueryUI.Core.Service
{
    public class AnimalsService : IAnimalsService
    {
        private readonly IAnimalsRepository _animalsRepository;

        public AnimalsService(IAnimalsRepository animalsRepository)
        {
            _animalsRepository = animalsRepository;
        }

        public AnimalsDto GetAnimalsForGameWithCorrectAnswer(int numberOfAnimals, string previousAnimal)
        {
            AnimalsDto animalsDto = new AnimalsDto();
            animalsDto.Animals = _animalsRepository
                .GetAll()
                .Where(a => a.Name != previousAnimal)
                .Shuffle()
                .Take(numberOfAnimals);

            animalsDto.CorrectAnswer = animalsDto.Animals.Shuffle().First().Name;

            return animalsDto;
        }
    }
}

This also makes testing easier because the tests can focus on making sure the service is doing what it should like this

using System;
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using GameUsingAspNetMVCandJQueryUI.Core.Repository;
using GameUsingAspNetMVCandJQueryUI.Core.Service;
using NBehave.Spec.NUnit;
using NUnit.Framework;
using Rhino.Mocks;

namespace GameUsingAspNetMVCandJQueryUI.Tests
{
    [TestFixture]
    public class AnimalsServiceTests
    {
        private IAnimalsService _animalsService;
        private IAnimalsRepository _animalsRepository;

        private readonly IQueryable<Animal> _animalsStub = new Animal[]
                           {
                               new Animal(){Name = "Cow"},
                               new Animal(){Name = "Pig"},
                               new Animal(){Name = "Sheep"},
                           }.AsQueryable();

        [SetUp]
        public void SetUp()
        {
            _animalsRepository = MockRepository.GenerateStub<IAnimalsRepository>();
            _animalsService = new AnimalsService(_animalsRepository);
        }

        [Test]
        public void Should_Exclude_Previous_Animal_When_Previous_Animal_Is_Passed_In()
        {
            // Arrange
            _animalsRepository.Stub(a => a.GetAll()).Return(_animalsStub);
            var previousAnimal = _animalsStub.First();

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal.Name);

            // Assert
            result.Animals.Count(a => a.Name == previousAnimal.Name).ShouldEqual(0);
        }

        [Test]
        public void Should_Return_All_Animals_When_No_Previous_Animal_Is_Passed_In()
        {
            // Arrange
            _animalsRepository.Stub(a => a.GetAll()).Return(_animalsStub);
            string previousAnimal = String.Empty;

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal);

            // Assert
            result..Animals.Count().ShouldEqual(3);
        }

        [Test]
        public void Should_Return_All_Animals_When_No_Previous_Animal_Is_Null()
        {
            // Arrange
            _animalsRepository.Stub(a => a.GetAll()).Return(_animalsStub);
            string previousAnimal = null;

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, previousAnimal);

            // Assert
            result.Animals.Count().ShouldEqual(3);
        }

        [Test]
        public void Correct_Answer_Should_Not_Be_Empty()
        {
            // Arrange
            _animalsRepository.Stub(a => a.GetAll()).Return(_animalsStub);            

            // Act
            var result = _animalsService.GetAnimalsForGameWithCorrectAnswer(3, null);

            // Assert
            result.CorrectAnswer.ShouldNotBeEmpty();
        }
    }
}

The LINQ Shuffle

Even though we have removed the previous answer, if the animals were returned as they are the answer would just be the next one in the list. So to keep the game exciting, a shuffle extension method is used to shuffle the answers.

using System;
using System.Collections.Generic;
using System.Linq;

namespace GameUsingAspNetMVCandJQueryUI
{
    public static class GameExtensions
    {
        public static IEnumerable<T> Shuffle<T>(this IEnumerable<T> items)
        {
            var rnd = new Random();
            IEnumerable<int> numbers = Enumerable.Range(0, items.Count()).OrderBy(r => rnd.Next());
            var randomItems = new List<T>();
            foreach (int number in numbers)
            {
                randomItems.Add(items.Skip(number).First());
            }
            return randomItems;
        }
    }
}

This can be unit tested as shown below

using System.Collections.Generic;
using System.Linq;
using GameUsingAspNetMVCandJQueryUI.Core.Models;
using NUnit.Framework;

namespace GameUsingAspNetMVCandJQueryUI.Tests
{
    [TestFixture]
    public class GameExtensionsTests
    {
        [Test]
        public void Can_Shuffle_Animals()
        {
            List<Animal> animals = new List<Animal>()
                           {
                               new Animal(){Name = "Cow"},
                               new Animal(){Name = "Pig"},
                               new Animal(){Name = "Sheep"},
                           };
            IList<Animal> result = animals.Shuffle().ToList();
            Assert.IsFalse(
                animals[0].Equals(result[0]) &&
                animals[1].Equals(result[1]) &&
                animals[2].Equals(result[2]),
                "Animals should have been shuffled");
        }
    }
}

What happens when a player opens the game in their browser?

When the page loads an Ajax call is made using jQuery to an Asp.Net MVC action method which returns a JsonResult.

   $.getJSON("/Game/GetAnimals",
            { numberOfAnimals: numberOfItemsToGet, previousAnimal: correctAnswer.text() },
            function(data) {
                addItems(data);
                $("#droppable").droppable(droppableOptions);
                assignDraggables();
                hideItemsForLevel();
                setUpSlider();
                setTimeout(function() {
                    instructions.text(instructionsText);
                    items.show();
                }, 1000);
            });

Two parameters are passed to the action method, one for the previous answer and the other for the number of animals required. The reason for this is because we don’t want to transfer more data over the wire than required, why return fourteen animals when only six are required?

The ‘GetAnimals’ Asp.Net MVC action method shown below serializes the view model returned by the service layer into JSON.

using System.Web.Mvc;
using GameUsingAspNetMVCandJQueryUI.Core.Service;

namespace GameUsingAspNetMVCandJQueryUI.Controllers
{
    [HandleError]
    public class GameController : Controller
    {
        private readonly IAnimalsService _animalsService;

        public GameController(IAnimalsService animalsService)
        {
            _animalsService = animalsService;
        }

        public ActionResult Index()
        {
            return View("Index");
        }

        [OutputCache(NoStore = true, Duration = 0, VaryByParam = "*")]
        public JsonResult GetAnimals(int numberOfAnimals, string previousAnimal)
        {
            return Json(_animalsService.GetAnimalsForGameWithCorrectAnswer(numberOfAnimals,previousAnimal));
        }
    }
}

Notice how I have to be explicit about how I do NOT want the JsonResult to be cached. If you don’t add this Internet Explorer will cache the result and you will get the same animals.

Using the jQuery and jQuery UI in the ASP.NET MVC View

The JavaScript used the demo was good enough to perform the dragging and dropping of pictures so the good news is we can use it again here.

An additional feature I have added is to allow the player to change the difficulty of the game by choosing how many animals are shown on the screen.

To do this I used the jQuery UI slider and jQuery fade functionality. The reason I used fade rather show/hide in jQuery was because I didn’t want the animals to move position when a user changed the difficulty as this would have resulted in a poor user experience by confusing the player.

Currently the message which tells the player if they have selected an incorrect answer is shown when the user stops dragging the animal. This is a problem because if the user drags a correct animal but doesn’t drop it on the droppable a message isn’t shown. If I find a fix for this I’ll update the code and this post.

Jag Reehal’s Final Thought on ‘Creating the animals game using Asp.Net MVC, jQuery and jQueryUI’

I’ve been using jQuery for a while now and I still love it.

The jQuery UI library is very good and the jQuery UI team have done a fantastic job creating demos and documentation.

I really like how you can create your own custom javascript file which only contains the features you require from the library.

No doubt some people will question why the service is returning a data transfer object. I could have returned a collection of animals to the ASP.NET MVC controller and have it create an object to pass to the view. The reason I didn’t do this is because I know the data transfer object will be used by another user interface layer (Silverlight) and because this would have bloated the controller and that’s not good. A best practice for ASP.NET MVC is to have skinny controllers.

The images for the animals used in the game are from http://www.openclipart.org.

Page 3 of 612345...Last »