Randomise your unit tests – lists

Following on from the previous post about benefits of randomising unit test inputs, the following deals with the unit testing of lists.
Create a list with random number of entries using the following extension method. The following uses the ForEach extension method for IEnumerable.
       public static IList ListFor(this Random random, 
            int min = MinForList, int max = MaxForList)
            where T : new()
            var list = new List();
            Enumerable.Range(1, random.Next(min, max))
                      .ForEach(x => list.Add(new T()));
            return list;

This will create a list with empty items. If the items need to be filled in, the following extension method can be helpful.
       public static IList FilledListFor(this Random random,
            Action action, int min = MinForList,
            int max = MaxForList)
            where T : new()
            var list = random.ListFor(min, max);
            return list;
In case of trivial inputs that need to be differentiated from each other, the Action above could be along the lines of following code:
        var customers = _random.FilledListFor(x =>
                           x.Id = _random.Next();
                           x.Name = _random.Next().ToString();
The list created above can now be provided to service/repository mock and the expected value for the unit test can be set on the list as given below. The elements to be skipped may also be chosen randomly. This removes the need to put in hard coded expected value/s.
       var expected = customers.Skip(5).First();
       expected.Name = "Input Search Parameter Here";

This provides a more succinct way of setting up unit tests that avoids hard coding expected values while using less lines of codes than the filling of lists line by line.

The completed code for these and other extensions can be found at GitHub.


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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s