Day 13 NUnit


The Source Code

This post is part of my Dot Net On Linux posts. All the source code is available on GitHub here


NUnit is a unit test framework which integrates nicely into monodevelop.

For setting up and inital how to see my inital post here.

I have a HowTo on NUnit which can be found here.

You can also find my cheat sheet here.

This post is just a placeholder for my .NET on Linux series.



HowTo – Linq in C#

Source Code

All source code can be found on GitHub here.

My cheat sheet for Linq can be found here.

This is part of my HowTo in .NET seriies. An overview can be seen here,

Linq Intro

LINQ provides a consistent and common API for querying and manipulating data sets from a range of data sources such as databases, XML and in memory data sets.

It provides functionality for querying and manipulating set data similar to SQL.

LINQ queries are strongly typed; the compiler will check for syntax and type safety.

Getting Started

To access LINQ you must import the System.Linq name space from within the System.Core.dll.

Linq can be performed upon any collection implementing IEnumerable and also System.Array.

A simple example could be:

var oldPeople = from p in people
where p.Age > 30
select p

Which selects all people who are are older than 30 into a collection implementing IEnumerable

The ‘natural language’ like syntax compiles down into extension methods which we could have implemented directly.

var oldPeople = people.Where( x => x.Age > 30 );

Deferred Execution

Queries are not actually evaluated until you iterate over the sequence; the execution is deferred. This means that modifying the data and using the same Linq result set will cause the result execution to be invoked twice. This allows you to always rely on your results reflected upon the latest version of the data. This does need to be treated with care to prevent unnecessary execution.

Immediate execution can be made by any number of extension methods defined by the Enumerable type such as ToArray(), ToDictionary<TSource,TKey>(), and ToList().

LINQ Queries and Non-Generic Collections

Apart from System.Array all other non generic collections can not be used with Linq however we can convert them into a generic collections (which implement IEnumerable with the OfType() function.

var goodCollection = BadCollection.OfType<TypeName>();

Lambda and Anonymous Delegates

Linq makes extensive use of anonymous delegates and Lambdas. If you are not up to speed on this you might want to read my post on this here.

Anonymous Types

Linq makes extensive use of anonymous types. If you are not up to speed on this you might want to read this <;, though in short, anonymous types allow creation of types on the fly similar to JSON.

var v = new { Name = "John", Age = 30 };


Filtering allows away of removing entities which are not required; a predicate or where clause.

The previous example was using the where statement for both extension and natural language to filter out people based upon their age.

var oldPeople = people.Where (x => x.Age < 30);
var count = (from p in people
             where p.Age < 30
             select p).Count ();

There where extension method can also provide the element ordinal or position index.

var oldPeopls = people.Where (( x, index ) => index <= 4 && x.Age < 30);

Any property, member variable or function can be called or drilled into for part of our query. The following example show how to find people who have children; children returns a collection of children that a parent has.

var count = people.Where (x => x.Children.Count () > 0);
var count = (from p in people
             where p.Children.Count () > 0
             select p).Count ();


The element functions allow selection of an element from the collection; the execution is not deferred but executed immediately.

First allows the selection of the first element in the collection.

var samplePeople = people.OrderBy (x => x.Name).First ();

First can also provide a Predicate delegate and be used to find the first element which passes the predicate.

var samplePeople = people.OrderByDescending (x => x.Name).First (x => x.Gender == Gender.Male);

The problem with First() is that if there are no elements in the collection or elements which pass the predicate run time error occurs. FirstOrDefault() allows returning of default(T) to prevent this error from happening. The function default(T) provides the default value for a value type e.g 0 for int, or null for a reference type.

var samplePeople = people.Where (x => x.Name == "No Match").FirstOrDefault ();

Any element can be referenced and retrieved by its ordinal position with the ElementAt function.

var samplePeople = people.OrderBy (x => x.Name).ElementAt (0);


Grouping is similar to SQL grouping with one major exception. In SQL any data projected into the result set has to either be a field which was provided in the group list or an aggregate.

Linq simply partitions the collection into distinct groups with all data from all elements available regardless of their involvement in the group list. Combined with anonymous types we can have a lot of control over the grouping and the result set.

The following example groups people by gender and then creates an anonymous type containing the gender and the count of people in each group.

Linq automatically provides the Key field on the grouped result set; here we use it to populate the ‘Key’ field which we create on the anonymous type and will contain the gender.

// Group by gender and count...
var samplePeople = people.GroupBy (x => x.Gender).OrderBy (x => x.Key).
	Select (grp => new { Key = grp.Key,  Value = grp.Count ()});
// Group by gender and count...
var samplePeople = from p in people
	group p by p.Gender into gens
	select new { Key = gens.Key, Value = gens.Count()};

As previously mentioned all data is available from the grouped data. This next example provides the value element in our anonymous type as an order list of people by name with all the original data in tact.

// Split into groups of gender by grouping on Name
var samplePeople = people.GroupBy (x => x.Gender).OrderBy (x => x.Key).
	Select (grp => new { Key = grp.Key,  Value = grp.OrderBy (x => x.Name)});
var samplePeople = from p in people
	group p by p.Gender into gens
	select new { Key = gens.Key, Value = gens.OrderBy( x => x.Name)};

We can also group on multiple keys via anonymous types.

var samplePeople = people.GroupBy (key => new { key.Gender, key.Age},
(key, group ) => new { key.Gender, key.Age, Count = group.Count()});


Projection provides a way of creating a new collection from the current set by projecting the ex sting data into it along with other Linq functions such as Count() and Sum() or pretty much anything you want.

Select provides a way of selecting a combination of fields into the result set. Here we create a list of strings by projecting the Name field into the result set.

var allFemaleNames = people.Where (x => x.Gender == Gender.Female).Select (x => x.Name);
var allFemaleNames = from p in people
           			where p.Gender == Gender.Female
           			orderby p.Name descending
					select p.Name;

Projection is often used with anonymous types to create new types on the fly as required. Here we create a new type with Age and Name of all females.

var parentsNameAndAge = people.Where (x => x.Gender == Gender.Female).Select (x => new { Name = x.Name, Age = x.Age });
var parentsNameAndAge = from p in people
	where p.Gender == Gender.Female
	select new { Name =  p.Name, Age = p.Age };

SelectMany provides a way of flattening a collection of collections. Children on parent is a collection of children for a parent. Here we create a collection of all Children in one collection. The where clauses is provided on people to select only females and then upon the flattened children collection to select only boys; ie all boys who have mums.

var boysWithFemaleParents = people.Where (x => x.Gender == Gender.Female).
	SelectMany (x => x.Children).
		Where (x => x.Gender == Gender.Male);
var boysWithFemaleParents = from parent in people
	where parent.Gender == Gender.Female
	from children in parent.Children
	where children.Gender == Gender.Male
	select children;


Ordering functions provide…… ** wait for it ** …. ordering functionalit.

Elements in a collection can be ordered ascending with the OrderBy function.

var orderdPeople = people.OrderBy (x => x.Name);
var orderdPeople = from p in people
	orderby p.Name
	select new { p.Name, p.Age, p.Children, p.Gender };

OrderBy() function can take an class implementing the IComparer to provide any required comparisons. StringComparer class contains a few predefined comparisons for strings with and without case sensitivity.

var orderdPeople = people.OrderBy (x => x.Name, StringComparer.CurrentCultureIgnoreCase);

Ordering can be made by a field descending

var orderdPeople = people.OrderByDescending (x => x.Name);
var orderdPeople = from p in people
	orderby p.Name descending
	select new { p.Name, p.Age, p.Gender, p.Children };

Ordering can also be made upon multiple fields by using either ThenBy or ThenByDescending after OrderBy or OrderByDescending.

var orderdPeople = people.OrderBy (x => x.Age).ThenByDescending (x => x.Name);

Natural language Linq supports multiple ordering fields similar to sql by separating the field names by commas.

var orderdPeople = from p in people
	orderby p.Age, p.Name descending
	select new { p.Name, p.Age, p.Gender, p.Children };

Elements Can be reversed with the Reverse() method.

var orderdPeople = people.OrderBy (x => x.Name).Reverse ();

Some of the Linq extension methods are not supported through natural Linq though the extension methods can be called in situ of the natural language.

var orderdPeople = (from p in people
	orderby p.Name
    select new { p.Name, p.Age, p.Gender, p.Children }).Reverse ();


Quantifiers provide functionality to asses if any or all elements in the collection pass a predicate.

Any() returns true if any elements pass a predicate and is useful to be called before First(Predicate); though this is quite wasteful.

var isAnyPeople = people.Any (x => x.Gender == Gender.Unknown);

It does not require a delegate as a parameter and can be called to asses if a collection or current Linq expression will evaluate to an empty collection or not.

var isAnyPeople = (from p in people
                   where p.Gender == Gender.Unknown
                   select p).Any ();

Here is a good example of allowing a combination of natural Linq and Linq extension methods. Children property returns a collection of children for that person.

var isAnyPeople = from p in people
    			  where p.Children.Any (child => child.Gender == Gender.Unknown)
				  group p by p.Gender into genders
                  select new { Gender = genders.Key, People = genders};

When ever an IEnumerable is provided a new Linq expression can be started. Here we are selecting any parents who have boys for children.

var isAnyPeople =
	people.Where (z => z.Children.Any (child => child.Gender == Gender.Male)).
                GroupBy (x => x.Gender).
				Select (y => new { Gender = y.Key, People = y });

The All() function can be used to make sure that all elements in the collection pass the predicate; there is no parameterless overload.

var allMale = people.All (x => x.Gender == Gender.Male);

Below is an example of combining Any with grouping. We group the data by gender with a predicate of having all children as girls; anyone who does not have all girls for children are omitted from the result set.

var isAll = from p in people
	group p by p.Gender into genders
	where genders.All( x => x.Children.All (child => child.Gender == Gender.Female))
	select new { Gender = genders.Key, Value = genders};


Conversions provide a way of converting of translating data. We have already talked about ToArray() and ToList() which can be used to prevent the deferred execution and push the results set into a collection.

var samplePeople = people.OrderBy (x => x.Name).ToArray ();
var samplePeople = people.ToList ();

ToDictionary creates a dictionary of all elements in keyed upon the return fields from the Func delegate provided. The example above creation a Dictionary<string,Person> where the key is a string of peoples names.

var samplePeople = people.ToDictionary (x => x.Name);

OfType as mentioned previouslt is a way to convert an array into an IEnumerable to allow Arrays to have Linq executed on them. It actually creates a collection of only the specified type ommitting anything which is not of the provided type; reemember array is a collectio of objects.

Below we have an array of ints and decimals, calling OfType() creates a collection of IEnumeranle of the two decimal elements within the array. All other elements are ommitted.

// Filter out those which are note od typw double
var sampleIntNumbers = new List<object> (){ 1,2,3,4,5,6m,7,8m,9,10};
var sampleDecimalNumbers = sampleIntNumbers.OfType<decimal> ().ToList ();

This might not be required functionality, we could have used either Cast or Convert create a collection with all elements contained within.

The example above could have been written above.

var sampleObjNumbers = new List<int> (){ 1,2,3,4,5,6,7,8,9,10};
var sampleIntNumbers = sampleObjNumbers.ConvertAll<double> (x => Convert.ToDouble (x));

If all elements implement an interface or have a common ancestory we could have used the Cast function.

// Cast can only cast to Implemented Interfaces and classes within the hierachy
// Convert all data ti
var sampleObjNumbers = new List<object> (){ 1,2,3,4,5,6m,7,8,9,10};
var sampleIntNumbers = sampleObjNumbers.Cast<int> ().ToList ();

ConvertAll can be used for a lot more purposes, below we convert people list a list of strings which contains peoples names in upper case.

// Convert all strings to Upper Case
var upperCaseNames = people.Select (x => x.Name).OrderBy (x => x).ToList ().ConvertAll<string> (x => x.ToUpper ());


Aggregates are similar to SQL aggregates. They are functions which return a single result value for a set of data; the simplest example being Count().

var count = people.Count ();
var count = (from p in people
			 select p).Count ();

Count can also take a Predicate delegate; the count value will be the number records passing the provided predicate.

var count = people.Count (x => x.Gender == Gender.Male);
var count = (from p in people
             where p.Gender == Gender.Male
             select p).Count ();

Nested counts can help with projections. Here we translate the data into a new collection of Name and ChildrenCount. Name being the persons name and ChildrenCount being the count of girls the person has.

var samplePeople = people.Select
	(x => new { Name = x.Name, ChildrenCount = x.Children.Count (y => y.Gender == Gender.Female)});
var samplePeople = from p in people
				   select new { Name= p.Name, ChildrenCount =
						  (from c in p.Children
	                 	  where c.Gender == Gender.Female
	                 	  select c).Count () };

Sum provides a way of adding up all number values. Here we are adding up all the counts of children into variable.

var childrenCount = people.Sum (x => x.Children.Count ());

The example below shows building up the Sum with Where clauses to get the count of boys who have fathers.

var maleSonsCount = people.Where (x => x.Gender == Gender.Male).Sum (x => x.Children.Where (y => y.Gender == Gender.Male).Count ());

Min provides the Math.Min or minimum value from a set. Here we find the minimum number of children a person has.

var minChildrenCount = people.Min (x => x.Children.Count ());
var children = from p in people
	group p by p.Gender into peopleGenders
		let minKids = peopleGenders.Min( x => x.Children.Count())
	select new { Gender = peopleGenders.Key, Value = peopleGenders.Count() };

Max provides the Math.Max or maximum value from a set. Here we find the maximum number of children a person has.

var maxChildrenCount = people.Max (x => x.Children.Count ());

Average is the mean average; i.e add up all values and divide by the number of elements.

var avgChildrenCount = people.Average (x => x.Children.Count ());

The example below groups the data into genders and then provides an anonymous type of Gender, Average, Min and Max of the number of children for each gender type.

var samplePeople = people.GroupBy (x => x.Gender).
	Select (y => new { Key = y.Key,
		Average = Math.Round (y.Average (z => z.Children.Count ()), 2),
		Min = y.Min (z => z.Children.Count ()),
		Max = y.Max (z => z.Children.Count ())}


Set functions provides distinct, union, intersection and join functionality.

Distinct removes all duplicated data within a collection to provide a result set with distinct elements.

var numbers = new List<int> (){ 1,1,2,2,3,4,5 };
var distinctNumbers = numbers.Distinct ();
var distinctNumbers = ( from p in people
                        orderby p.Name
                        select p.Name  ).Distinct();

Distinction works on equality. Custom equality checks can be provided by providing an IEqualityComparer.

A random example but here we provide an equality check for people only by their gender. The example then projects the gender into a list which is ordered by Gender; ie we are getting a distinct list of genders ordered within our initial collection.

public class PersonSexComparer : IEqualityComparer<Person>
	public bool Equals (Person x, Person y)
		return x.Gender == y.Gender;

	public int GetHashCode (Person obj)
		return obj.Gender.GetHashCode ();


var distinctSex = people.Distinct (new PersonSexComparer ()).
	OrderBy (x => x.Gender).Select (y => y.Gender);

Union provides a way to combine sets of data. Here we create a super set of people and children. The SelectMany flatens all children into a collection before unioning them with the collection of parents.

var allPeople = people.Union (people.SelectMany (x => x.Children)).
	OrderByDescending (x => x.Gender).ThenBy (x => x.Name);
var allPeople = people.Union ( from p in people
                  from c in p.Children
                 select c);

Intersection provides a result set of elements which exist in both collections.

var groupOne = new List<int> (){ 1,2,3,4,5};
var groupTwo = new List<int> (){4,5,6,7};
var groupInter = groupOne.Intersect (groupTwo).OrderBy (x => x);

No real equivalent in natural link though the contains method can allow similar functionality.

var groupOne = new List<int> (){ 1,2,3,4,5};
var groupTwo = new List<int> (){4,5,6,7};
var groupInter = from n in groupOne
		where groupTwo.Contains(n)
		select n;

Except provides a ‘Not In’ functionality. Al elements in the first set which are not in the second will be found in the result set.

var groupOne = new List<int> (){ 1,2,3,4,5};
var groupTwo = new List<int> (){4,5,6,7};
var groupExcept = groupOne.Except (groupTwo).OrderBy (x => x);
var groupOne = new List<int> (){ 1,2,3,4,5};
var groupTwo = new List<int> (){4,5,6,7};
var groupExcept = from n in groupOne
	where !groupTwo.Contains(n)
		select n;

Concat provides a way of combining the elements of two collections into one.

var groupOne = new List<int> (){ 1,2,3,4,5};
var groupTwo = new List<int> (){4,5,6,7};
var groupExcept = groupOne.Concat (groupTwo).OrderBy( x=> x);

SequenceEquals provides a check of whether all elements in two collections are equal and in the same order.

var groupOne = new List<int> (){ 1,2,3,4,5};
var groupOneAgain = new List<int> (){ 1,2,3,4,5};
Assert.IsTrue (groupOne.SequenceEqual(groupOneAgain));

Join is similar to SQL join; we can match two elements in two collections and work upon all data contained.

Here we have a collection which describes each element in the Gender enumerator. We can join between people and gender description collection and project all fields into the result set.

var foo = people.Join( genderDescriptions,
                      aPerson => aPerson.Gender,
                      aDesc => aDesc.Gender,
                      ( aPerson, aDes ) => new { Name = aPerson.Name, Gender = aPerson.Gender, Desc = aDes.Descripion} );
var foo = from aPerson in people
	join aDes in genderDescriptions on aPerson.Gender equals aDes.Gender
select new { Name = aPerson.Name, Gender = aPerson.Gender, Desc = aDes.Descripion};


Partitioning provides a way of taking or skipping elements in a collection,

Take(x) takes the first x elements in a collection.

var firstThreePeople = people.Take (3);

Here we combine take with where to take the first two males.

var firstTwoPeople = people.Where (x => x.Gender == Gender.Male).Take (2);

Here we add into the mix an anonymous type to create a new type with Name, Age, Gender and Children of the first two males.

var firstTwoPeople =
	(from p in people
	  where p.Gender == Gender.Male
	  select new { p.Name, p.Age, p.Gender, p.Children }).Take (2);

Skip is the opposite of take. Skip(x) takes all but the first x elements. Here we take all but the first 4 people.

var allButFirstFour = people.Skip (4);

TakeWhile provides a function to take all elements in a collection while a predicate is met. Any elements which pass the predicate and follow an element which fails the predicate will be omitted from the result set.

var allButFirstFour = people.TakeWhile (x => x.Gender == Gender.Male);

SkipWhile provides the opposite of TakeWhile. All initial elements passing the predicate will be omitted until the first element passes the predicate.

var allButFirstFour = people.SkipWhile (x => x.Gender == Gender.Male);


Generation functions include Range and Repeat; these provide a way of creating a collection of type T.

Range provides a way of creating a collection of integers between (and including) a start and end int.

var sampleInts = Enumerable.Range(1, 10);

Repeat takes type T and creates a collection of int times. Here we create a collection of 10 1’s.

var sampleInts = Enumerable.Repeat(1, 10);

Spotify won’t install due to dependency with libssl0.9

libssl0.9 has moved onto version libssl1 though Spotify currently has prerequisite dependency of no more than libssl0.9 and won’t install.

You can safely install the two side by side. Download the required version from squeeze repositories and install with one of the following scripts:

32 bit:

sudo wget && sudo dpkg -i libssl0.9.8_0.9.8o-4squeeze13_i386.deb 

64 bit

sudo wget && sudo dpkg -i libssl0.9.8_0.9.8o-4squeeze13_amd64.deb

SSD Instability under Linux

SSD Instability

I was having some serious instability with my new SSD under Linux. Installation with LMDE was not possible and Ubuntu kept on locking up when copying files.

It seems that the HD is too quick and the native queuing of commands can cause instability; disabling this has made my machine more stable and I have not noticed any deterioration in performance.

Add libata.force=noncq somewhere on the Linux line of your currently kernel in the grub config file.

sudo pluma /boot/grub/grub.cfg

menuentry "Ubuntu (on /dev/sda1)" --class gnu-linux --class gnu --class os {
	insmod part_msdos
	insmod ext2
	set root='(/dev/sda,msdos1)'
	search --no-floppy --fs-uuid --set=root xxxxxxx
	linux /boot/vmlinuz-3.5.0-23-generic root=UUID=xxxxxxxx ro quiet splash libata.force=noncq $vt_handoff
	initrd /boot/initrd.img-3.5.0-23-generic

More information about libata.force-noncq can be found here.

Also you can add this into a live disc or current grub boot prompt but pressing the tab or | key. A screen shot is shown below.



HowTo – XUnit

Source Code

All source code can be found on GitHub here.

My cheat sheet for XUnit can be found here.

This is part of my HowTo in .NET seriies. An overview can be seen here,


XUnit is a unit test framework. The features appear to be somewhat lacking when compared to NUnit but it aims to only provide the functionality which is intended to be common and supports good unit testing structure. For example in NUnit [TestFixureSetUp] does not promote test isolation so an equivalent functionality have been purposefully omitted.

There is also no fluent assertions but there are 3rd party dlls available instead.

XUnit also differs from other unit test frameworks by not relying on attributes as much. For example constructor and dispose methods are used for test set up and tear down functions.

Basic Test Creation

The following examples consists of a simple class with a parameter-less constructor that implements IDisposable. There is also one public method decorated with [Fact] attribute.

The constructor is our test setup function.

The Dispose is our test tear down function.

The Method with [Fact] is our test.

public class AccountTests : IDisposable		// Allows Test TearDown via Dispose()

	public AccountTests()

	public void SimpleExample()

	public void Dispose()



Common set up code can be refactored out to a helper class and injected in automatically via the IUseFixture interface and implementing its only method SetFixture(T t)

public class AccountTests : IUseFixture<AccountTests.TestSetUpClass> // Allows Test Set Up via injected class

	public void SetFixture(TestSetUpClass setupClass)
	    // Can inject a class to provide any set up here.

	public class TestSetUpClass
	    public void AnyFunction()
		// Set up code goes in here.

InLineData allows multiple traversals of the same test with different parameters. It can take any number and types of parameters though they have to match the method signature which they are decorating.

The following example will result in 3 tests with the parameters, {1, true}, {2, true}, {3, false}

InlineData(1, true),
InlineData(2, true),
InlineData(3, false)]
public void InlineDataExample(int number, bool expectedResult)
    Console.WriteLine("AccountTests.DemoSimpleTestWithInLineData(int {0}, bool {1})", number, expectedResult);
    Assert.Equal(number < 3, expectedResult);


Similar to InLineData though the test data can be injected in from a property.

The property should returns IEnumerable where the object array contains the same matching parameters to the method signature of the test method.

public static IEnumerable<object[]> SamplePropertyDataProperty
        yield return new object[] { 1, true };
        yield return new object[] { 2, true };
        yield return new object[] { 3, false };

public void PropertyDataExample(int number, bool expectedResult)
    Console.WriteLine("AccountTests.PropertyDataExample(int {0}, bool {1})", number, expectedResult);
    Assert.Equal(number < 3, expectedResult);


Assertions are conditions which will cause our test to fail or pass. Each assertion will cause an exception to be thrown when the condition is not met. The test runner will handle the exception, fail the test and start running the next test. If a unit test runs to the end without an exception then the test is considered as passed.

If an exception is thrown which is not part of an Assert but inside the test it is considered as failed.

If an exception is thrown inside the code under test which is not expected the test is considered as failed. If an exception being thrown is the expected result then special exception asserts must be used.

Contains asserts that something is found within a reference type which implements IEnumerable or IEnumerable ( collection ).

A string is a collection of chars and implements IEnumerable.

Assert.Contains("n", "FNZ", StringComparison.CurrentCultureIgnoreCase);
Assert.Contains("a", new List<String> { "A", "B" }, StringComparer.CurrentCultureIgnoreCase);

Does not contain ensures that something is not within a collection or IEnumerable.

Assert.DoesNotContain("n", "FNZ", StringComparison.CurrentCulture);
Assert.DoesNotContain("a", new List<String> { "A", "B" }, StringComparer.CurrentCulture);

Empty and not empty ensures that a collection of IEnumerable is or is not empty.

Assert.Empty(new List<String>());
Assert.NotEmpty(new List<String> { "A", "B" });

Equality checks with the ability to pass in a IComparer and also a precision for number of dp; equality up to x decimal places.

The ability to compare all elements within a collection against another collection is also catered for with an overloaded method for IComparer

Assert.Equal(1, 1);
Assert.Equal(1.13, 1.12, 1); // Precsions Num DP
Assert.Equal(new List<String> { "A", "B" }, new List<String> { "a", "b" }, StringComparer.CurrentCultureIgnoreCase);

Assert.NotEqual(1, 2);
Assert.NotEqual(new List<String> { "A", "B" }, new List<String> { "a", "b" }, StringComparer.CurrentCulture);

Conditions for asserting boolean logic, is and is not null.


Range comparer ensures that a value is greater than and equal to a number and also less than or equal to another.

Assert.InRange(1, 0, 10);
Assert.NotInRange(-1, 0, 10);

Assertions to ensure a memory allocation is of a required type.

Assert.IsType(Type.GetType("System.Int32"), 1);
Assert.IsNotType(Type.GetType("System.Double"), 1);

Identity ( is the same object ) assertions are performed with Same and NotSame functions.

var foo = new object();
var moo = new object();
Assert.Same(foo, foo);
Assert.NotSame(foo, moo);

Exceptions can be tested for with the Throws function. The code under test needs to be provided inside a delegate otherwise the exception is not expected and will cause the unit test to fail.

Assert.Throws<Exception>(() => { throw new Exception(); });

Custom IEqualityComparer

Custom comparers can be written to provide bespoke equality comparison. This is not part of XUnit though we can use this functionality with our assertions.

In the example below we have a class called Foo which has an Id and a Name. Id is an int and Name is a string. We want equality to be based upon the Id and the Name case insensitive.

We create a class implementing IEqualityComparer and implement the Equals and GetHasCode functions. Equals is our main function here as this is what our unit test will be using for the equals assertions.

public class Foo
    public int ID { get; set; }
    public string Name { get; set; }

public class FooComparer : IEqualityComparer<Foo>
    public bool Equals(Foo x, Foo y)
        return x.ID == y.ID && x.Name.Equals(y.Name, StringComparison.CurrentCultureIgnoreCase);

    public int GetHashCode(Foo obj)
        return obj.ID.GetHashCode();

We can pass in an instance of our custom comparer to the Assert.Equal

Assert.Equal(new Foo { ID = 1, Name = "A Name"), new Foo { ID = 1, Name = "a name"), new FooComparer());

HowTo – NUnit – Fluent Assertions

Source Code

All source code can be found on GitHub here.

My cheat sheet for NUnit can be found here.

This is part of my HowTo in .NET seriies. An overview can be seen here,


NUnit is a unit test framework for .net; it is very mature and contains lots of features when compared to XUnit.

This post is part of a 3 part post on NUnit:

  1. NUnit Features
  2. Assertions
  3. Fluent Assertions

This post covers the Fluent Assertions.

Most of these are self explanatory so my words will at time be minimal; highlighting or obscure points.

The examples given are the simplest self explantory way to define a pass using the assertion.


Fluent is a programming style or design pattern. Methods return the class instance to allow another method on the test to be called by simply writing the next method on the same line of code.

The reason why this coding is nice as it allows grouping parameters together and allowing the method names to describe what happens.

Consider the following example.

// Fluent
Assert.That (1.1, Is.EqualTo (1.01).Within (10).Percent);

An equivalent though theoretical equivalent on the non fluent assertions.

// Non Fluent
Assert.EqualToOrWithin (1.1, 1.01, 10);

Both methods only actually have one method executing ‘functional’ code though without an understanding of the parameter names or even what the methods do the fluent syntax is more verbose and easier to read; especially if you are new to the code.

Numerical Equality

Numerical equality with error tolerance and units. No units would use the tolerance value directly, the percent tolerance allows the difference between the result and expected result up to within the provided percent.

Assert.That (1, Is.EqualTo (1));
Assert.That (1, Is.Not.EqualTo (2));
Assert.That (1.1, Is.EqualTo (1.2).Within (0.1)); // Allow a tolerance exact value used
Assert.That (1.1, Is.EqualTo (1.01).Within (10).Percent); // Pass tolerance within percent

Float Equality

Float tolerance allows error tolerance ignoring the last x placed digits.

Assert.That (20000000000000004.0, Is.EqualTo (20000000000000000.0).Within (1).Ulps); // Pass tolerance with units of last place

The tolerance unit has many types for tolerating against all fractions of a time of day; day, hour, minutes etc.

Assert.That (DateTime.Today, Is.EqualTo (DateTime.Today));
Assert.That (DateTime.Now, Is.Not.EqualTo (DateTime.Now));
Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (TimeSpan.FromSeconds (1))); // Time based pass tolerances
Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Days);
Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Hours);
Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Minutes);
Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Seconds);
Assert.That (DateTime.Now, Is.EqualTo (DateTime.Now).Within (1).Milliseconds);

String Equality

String equality with and without case sensitivity. Also comparing all elements within a collection.

Assert.That ("Foo!", Is.EqualTo ("Foo!"));
Assert.That ("Foo!", Is.Not.EqualTo ("FOO!"));
Assert.That ("Foo!", Is.EqualTo ("FOO!").IgnoreCase);
Assert.That (new List<string> (){ "FOO!"}, Is.EqualTo (new List<string> (){ "Foo!"}).IgnoreCase);


Assertions for comparing collections and their elements for equality; equality is made if each element in the same position (irrelevant of the collection and the element types) are equal and the amount of elements inside both collections is the same.

AsCollection provides a way to ‘flatten’ a jagged array or collection of collections to compare just the elements. In the example below {{1,2},{3,4}} flattens to {1,2,3,4}.

Assert.That (new double[] {1.0,2.0,3.0}, Is.EqualTo (new int[] {1,2,3}));
Assert.That (new double[] {1.0,2.0,3.0}, Is.Not.EqualTo (new int[] {1,2,3, 4}));
Assert.That (new double[] {1.0,2.0,3.0,4.0}, Is.EqualTo (new  int[,] {{1,2}, {3,4}}).AsCollection); // Compare data and not collection (flattens a collection of collections)

Customer Comparer

A custom comparer can be written for comparison between two objects of the same type. Create a class which implements IEqualityComparer and use the EqualTo assertion along with providing an instance of the comparer class.

Assert.That( int.MinValue, Is.EqualTo(int.MaxValue).Using(new WhoCaresComparer()));

public class WhoCaresComparer : IEqualityComparer<int>
    public bool Equals(int b1, int b2)
		return true;

    public int GetHashCode(int aNumber)
		return aNumber.GetHashCode();


Identify assertions check that two reference types are the same instance.

Assert.That( string.Empty, Is.SameAs(string.Empty));
Assert.That( new object(), Is.Not.SameAs(new object()));

A few conditional assertions for checking reference types are null or not null, collections are empty and unique etc.

Assert.That( string.Empty, Is.Not.Null);
Assert.That( true, Is.True);
Assert.That( true, Is.Not.False);
Assert.That( double.NaN, Is.NaN);
Assert.That( string.Empty, Is.Empty);
Assert.That( new List<int>(), Is.Empty);
Assert.That( new List<int>(){1,2,3}, Is.Unique);


A number of assertions for comparing types which are numbers. AtLeast is the same as GreaterThanOrEqualTo and AtMost() is the same as LessThanOrEqualTo.

Assert.That(1, Is.LessThan(2));
Assert.That(1, Is.GreaterThan(0));
Assert.That(1, Is.LessThanOrEqualTo(1));
Assert.That(1, Is.GreaterThanOrEqualTo(1));
Assert.That(1, Is.AtLeast(0));	// Same as GreaterThanOrEqualTo
Assert.That(1, Is.AtMost(2)); 	// Same as LessThanOrEqualTo
Assert.That(1, Is.InRange(1,2));

File Paths

File path assertions; comparing the file path name only.

All path names are converted to ‘canonical’ path before comparing; full direct path to file. For example ‘~/Foo.txt’ would not fail against ‘/home/Luke/Foo/txt’ for user name Luke.

SubPath allows checking that the file under test is within a compared directory path.

SamePathOrUnder is the same as SubPath though won’t fail if the path names are the same.

File and directory paths can both be provided.

Assert.That( "MyFile.txt", Is.SamePath("MyFile.txt"));
Assert.That( "MyFile.txt", Is.SamePath( "MYFILE.TXT" ).IgnoreCase );
Assert.That( "MyFile.txt", Is.SamePath("MyFile.txt").RespectCase);
Assert.That( "/usr/bin", Is.SubPath("/usr"));			// directory exists within another
Assert.That( "/usr/bin", Is.SamePathOrUnder("/usr"));	// SamePath or SubPath

Type Constraints

Allow comparison that an instance is of a type, ancestor or can be cast to or from a type.

Assert.That(new MemoryStream(), Is.InstanceOf<Stream>());  // Is type or ancestor
Assert.That(new MemoryStream(), Is.TypeOf<MemoryStream>()); // Is type and not ancestor
Assert.That(new object(), Is.AssignableFrom<MemoryStream>()); // Can be assigned from
Assert.That(new MemoryStream(), Is.AssignableTo<Stream>()); // Can be assignable to

String Comparison

Comparison of strings for their contents with and without case sensitivity.

Assert.That( "Foo", Is.StringContaining( "o" ) );
Assert.That( "Foo", Is.StringContaining( "O" ).IgnoreCase );
Assert.That( "Foo", Is.StringStarting( "F" ) );
Assert.That( "Foo", Is.StringEnding( "o" ) );
Assert.That( "Foo", Is.StringMatching( "^[F]" ) ); // Regular ecpression match

Collection comparison for comparing all entities; all very self explanatory with the fluent interface.

Equivalent compares entities and not their order; i.e performs a sort prior.

Assert.That( new List<int>(){1,2,3}, Has.All.GreaterThan(0) );
Assert.That( new List<int>(){1,2,3}, Is.All.GreaterThan(0) );
Assert.That( new List<int>(){1,2,3}, Has.None.GreaterThan(4));
Assert.That( new List<int>(){1,2,3}, Has.Some.GreaterThan(2));
Assert.That( new List<int>(){1,2,3}, Has.Count.EqualTo(3));
Assert.That( new List<int>(){1,2,3}, Is.Unique);
Assert.That( new List<int>(){1,2,3}, Has.Member(1));  // Contains
Assert.That( new List<int>(){1,2,3}, Is.EquivalentTo( new List<int>(){3,2,1})); // Same data without caring about the order
Assert.That( new List<int>(){1,2,}, Is.SubsetOf( new List<int>(){3,2,1})); // All are contained.

Property Constraint

Ability to compare a property value of a class and a required value. There are some predefined property names for exceptions message and inner exception.

Assert.That( new List<int>(), Has.Property("Count").EqualTo(0));  // Checks public property
Assert.That( new List<int>(), Has.Count.EqualTo(0));			  // Same as Has.Property("Count").EqualTo(0)
Assert.That( string.Empty, Has.Length.EqualTo(0));				  // Same as Has.Property("Length").EqualTo(0)
Assert.That ( new Exception("Foo"), Has.Message.EqualTo("Foo"));  // Exception has message
Assert.That ( new Exception("Foo", new ArgumentException("Moo")), // Inner exception is of type and has message


Ability to ensure that an exception is thrown and that it is of the right types and contents. Throws also contains references to some of the more common exceptions.

Assert.That (() => { throw new ArgumentException("Foo"); },

Assert.That (() => { throw new ArgumentNullException("Foo"); },

Assert.That (() => { throw new ArgumentNullException("Foo"); },

Assert.That (() => { }, Throws.Nothing);

Assert.That (() => { throw new Exception("Foo", new ArgumentException("Moo"));},

Assert.That (() => { throw new ArgumentException(); }, Throws.ArgumentException);

Compound Constraints

Compound constraints allow chaining checks together for when their readability is easier; i.e not intended to perform every check in one line of code as if we have to pay for a new line.

.And and & or Or and | can be used.

.Not and .All are also available.

Assert.That( 2, Is.Not.EqualTo( 1 ));
Assert.That( new List<int>(){ 1, 2, 3 }, Is.All.GreaterThan( 0 ) );

Assert.That( 1, Is.GreaterThan( 0 ).And.LessThan( 2 ) );  // .And amd & are the same
Assert.That( 1, Is.GreaterThan( 0 ) & Is.LessThan( 2 ) );

Assert.That( 1, Is.LessThan( 10 ) | Is.GreaterThan( 0 ) ); // .Or and | are the same
Assert.That( 1, Is.LessThan( 10 ).Or.GreaterThan( 0 ) );

Provides a thread sleep before performing the test. The second argument allows ‘pooling’ where assertion will happen after x time though the execution of the next line of code won’t be delayed.

Assert.That(() => { return true;}, Is.True.After(10));		// Passes after x time
Assert.That(() => { return true;}, Is.True.After(10, 10));	// Passes after x time and polling..

List Mapper

Allows all elements in a list to have a condition provided to them and a list of the expected results.

Assert.That(List.Map(new List<string>(){"1", "22", "333"}).Property("Length"), Is.EqualTo(new List<int>(){1,2,3}));

HowTo – NUnit – Assertions

Source Code

All source code can be found on GitHub here.

My cheat sheet for NUnit can be found here.

This is part of my HowTo in .NET seriies. An overview can be seen here,


NUnit is a unit test framework for .net; it is very mature and contains lots of features when compared to XUnit.

This post is part of a 3 part post on NUnit:

  1. NUnit Features
  2. Assertions
  3. Fluent Assertions

This post covers the Assertions which are provided and are used to conditionally pass or fail a unit test.

Most of these are self explanatory so I will keep my words to a minimum, highlighting only the main or more obscure points.

The examples given are the simplest self explanatory way to define a pass using the assertion.


Equality Assertions allow passing and failing of a test by comparing two objects or primitive types for equality; there are many overloads allowing passing in any value or reference type.

Assert.AreEqual (true, true);
Assert.AreNotEqual (true, false);


Identity Assertions provide the ability to pass or fail a test by comparing two objects for identity; i.e are they the same object instance or memory reference.

The following examples also provide the ‘Contains’ function which allows determination that an element is found within a collection.

Assert.AreSame (string.Empty, string.Empty);
Assert.AreNotSame (new object (), new object ());
Assert.Contains (string.Empty, new List<object> (){string.Empty});


Condition Assertions provide a mixture of tests from checking a boolean is either false or true, a reference type is or is not null and collection is or is not empty. Empty can be used on any element implementing IEnumerable including String which is an array of chars.

Assert.IsTrue (true);
Assert.IsFalse (false);
Assert.IsNull (null);
Assert.IsNaN (Double.NaN);
Assert.IsEmpty (new List<object> ());
Assert.IsEmpty (new List<object> ());
Assert.IsNotEmpty (new List<object> (){1});
Assert.IsNotEmpty ("Foo");


Comparison Assertions provide tests for comparing types which are numbers. The first parameter is the test object and the second parameter is the comparative object.

Assert.Greater (Decimal.MaxValue, Decimal.MinValue);
Assert.GreaterOrEqual (Decimal.MinValue, Decimal.MinValue);
Assert.Less (Decimal.MinValue, Decimal.MaxValue);
Assert.LessOrEqual (Decimal.MinValue, Decimal.MinValue);

The type assertions provide tests or determining an objects or types type.

Assignable determination uses Type.IsAssignableFrom() Method and determines is a type can be cast from another. More information can be seen here

Generic and non Generic implementations are also catered for:

Assert.IsInstanceOf<decimal> (decimal.MinValue);
Assert.IsNotInstanceOf<int> (decimal.MinValue);

Assert.IsNotAssignableFrom (typeof(List<Type>), string.Empty);
Assert.IsAssignableFrom (typeof(List<decimal>), new List<decimal> ());

Assert.IsNotAssignableFrom<List<Type>> (string.Empty);
Assert.IsAssignableFrom<List<decimal>> (new List<decimal> ());


Exception Assertions allow testing of exceptions being thrown; generic and non generic implementations are catered for.

Throws requires the exception type to be thrown explicitly.
Catch allows the exact exception type or any derived exception of that type.

The functions all take a delegate which should be used to call the method to be tested. If the method is called without the delegate the method will be called outside of the scope of the assert and outside of the scope of the test; the exception will fail the test despite being the required result!

Assert.Throws (typeof(ArgumentNullException), () => { throw new ArgumentNullException (); } );
Assert.Throws<ArgumentNullException> (() => { throw new ArgumentNullException (); } );

Assert.DoesNotThrow (() => { });

Assert.Catch (typeof(Exception), () => { throw new ArgumentNullException (); } );
Assert.Catch<Exception> (() => { hrow new ArgumentNullException (); });


A number of String assertions. The first parameter is the string under test and the second is the expected result. The test is case sensitive unless the method name states otherwise. IsMatch provides regular expression test.

StringAssert.Contains ("Foo", "MooFooMoo");
StringAssert.StartsWith ("Foo", "FooMoo");
StringAssert.EndsWith ("Moo", "FooMoo");
StringAssert.AreEqualIgnoringCase ("FOO", "foo");
StringAssert.IsMatch ("[0-9]", "1");

Assertions for collections, the method names and examples are self explanatory.

AreEqual requires each element to be the same in equality and the same position, AreEquivalent allows the elements to be in any position in the collection.

SubSet allows checking that all elements in a collection are found in another without caring if there are more elements to be found.

An example of overriding the ICompare for ordering is also provided.

// All Items Are....
CollectionAssert.AllItemsAreInstancesOfType (new List<decimal> (){ 0m }, typeof(decimal));
CollectionAssert.AllItemsAreNotNull (new List<decimal> (){ 0m });
CollectionAssert.AllItemsAreUnique (new List<decimal> (){ 0m, 1m });

// Equal and Equivalent
CollectionAssert.AreEqual (new List<decimal> (){ 0m }, new List<decimal> (){ 0m });
CollectionAssert.AreEquivalent (new List<decimal> (){ 0m, 1m }, new List<decimal> (){ 1m, 0m }); // Same as AreEqual though order does not mater
CollectionAssert.AreNotEqual (new List<decimal> (){ 0m }, new List<decimal> (){ 1m });
CollectionAssert.AreNotEquivalent (new List<decimal> (){ 0m, 1m }, new List<decimal> (){ 1m, 2m });  // Same as AreNotEqual though order does not matter

// Contains
CollectionAssert.Contains (new List<decimal> (){ 0m, 1m }, 1m);
CollectionAssert.DoesNotContain (new List<decimal> (){ 0m, 1m }, 2m);

CollectionAssert.IsSubsetOf (new List<decimal> (){ 1m }, new List<decimal> (){ 0m, 1m }); // {1} is considered a SubSet of {1,2}
CollectionAssert.IsNotSubsetOf (new List<decimal> (){ 1m, 2m }, new List<decimal> (){ 0m, 1m });

CollectionAssert.IsEmpty (new List<decimal> (){ });
CollectionAssert.IsNotEmpty (new List<decimal> (){ 1m });

// Ordered
CollectionAssert.IsOrdered (new List<decimal> (){ 1m, 2m, 3m });
CollectionAssert.IsOrdered (new List<string> (){ "a", "A", "b"}, StringComparer.CurrentCultureIgnoreCase);
CollectionAssert.IsOrdered (new List<int> (){ 3,2,1}, new ReverseComparer()); // Only supports ICompare and not ICompare<T> as of version 2.6

// IComparer

public class ReverseComparer : IComparer
		public int Compare (object a, object b)
			return ((int)b).CompareTo((int)a);


FileAssert provides ways to compare file contents or streams. There are overrides for providing a file name or stream. The tests are comparing the contents and not the file paths.

//  File Assert: various ways to compare a stream or file.
FileAssert.AreEqual (new MemoryStream (), new MemoryStream ());
FileAssert.AreEqual (new FileInfo ("MyFile.txt"), new FileInfo ("MyFile.txt"));
FileAssert.AreEqual ("MyFile.txt", "MyFile.txt");

FileAssert.AreNotEqual (new FileInfo ("MyFile.txt"), new FileInfo ("MyFile2.txt"));
FileAssert.AreNotEqual ("MyFile.txt", "MyFile2.txt");
FileAssert.AreNotEqual (new FileStream ("MyFile.txt", FileMode.Open), new FileStream ("MyFile2.txt", FileMode.Open));

Utilities allow immediate stopping of the unit tests with declaration of the test result:

Assert.Pass ();
Assert.Fail ();
Assert.Ignore ();
Assert.Inconclusive ();

Providing custom fail messages

Custom fail messages can be provided for all of the above assertions. The last parameter is always the custom fail message. These should not always be needed if you name your test methods as descriptively. If your assertions are checking completely different checks on your SUT ( subject under test ) such that custom fail messages are required; perhaps you should think of splitting the test up into multiple tests.

Assert.IsTrue(true, "A failed message here"); // also object[] params can be defined