Rhino Mocks Cheat Sheet

A cheat sheet for Rhino Mocks v 3.6 in C#

All source code can be found on GitHub here.

This post is part of my cheat sheet series.

You can see my HowTo here.

// *** STUB ****
// A stub is an object which is required to pass the SUT.

mocks.CreateStub<T>();

// The simple stub
var sut = MockRepository.GenerateStub<ISimpleModel>();
sut.Stub(x => x.Do()).Return(1);

// Stub Property
sut.Stub(x => x.AReadonlyPropery).Return(1); // Reaonly ( only get )
sut.AProperty = 2; // Stub Get

// Repeat
mock.Stub(x => x.Do()).Return(1).Repeat.Once();
mock.Stub(x => x.Do()).Return(2).Repeat.Twice();
mock.Stub(x => x.Do()).Return(3).Repeat.Times(3);

// Events
mock.Raise(x => x.Load += null, this, EventArgs.Empty);

// **** Arguments Conditional ****
// These can be used for Stub, Expect, AssertWasCalled and AssertWasNotCalled

// Ignore Arguments Conditional
sut.Stub(x => x.Do(Arg<int>.Is.Equal(1))).IgnoreArguments().Return(1);

// Is Conditionals
sut.Stub(x => x.Do(Arg<int>.Is.Anything)).Return(1);
sut.Stub(x => x.Do(Arg<int>.Is.Equal(1))).Return(1);
sut.Stub(x => x.Do(Arg<int>.Is.NotEqual(1))).Return(10);
sut.Stub(x => x.DoIFoo(Arg<Foo>.Is.Null)).Return(1);
sut.Stub(x => x.DoIFoo(Arg<Foo>.Is.NotNull)).Return(2);
sut.Stub(x => x.Do(Arg<int>.Is.LessThanOrEqual(10))).Return(1);
sut.Stub(x => x.Do(Arg<int>.Is.GreaterThan(10))).Return(2);
sut.Stub(x => x.DoIFoo(Arg<Foo>.Is.Same(foo))).Return(1);
sut.Stub(x => x.DoIFoo(Arg<Foo>.Is.NotSame(foo))).Return(2);
sut.Stub(x => x.DoIFoo(Arg<Foo>.Is.TypeOf)).Return(1);

// Matches Conditional
sut.Stub(x => x.Do(Arg<int>.Matches(y => y > 5))).Return(1);

// List Conditionals
sut.Stub(x => x.Do(Arg<List<int>>.List.Count(RIS.Equal(0)))).Return(0);
sut.Stub(x => x.Do(Arg<List<int>>.List.Element(0, RIS.Equal(1)))).Return(1);
sut.Stub(x => x.Do(Arg<List<int>>.List.Equal(new int[] { 4, 5, 6 }))).Return(2);
sut.Stub(x => x.Do(Arg<List<int>>.List.IsIn(1))).Return(1);
sut.Stub(x => x.Do(Arg<int>.List.OneOf(new int[] { 4, 5, 6 }))).Return(2);

// ByRef and Out parameters
sut.Stub(x => x.Do(Arg<int>.Is.Equal(1), ref Arg<int>.Ref(RIS.Equal(0), 10).Dummy)).Return(1);
sut.Stub(x => x.Do(Arg<int>.Is.Equal(1), Arg<string>.Is.Equal("Hello"), out Arg<int>.Out(10).Dummy)).Return(1);

// **** DYNAMIC MOCKS ***
// A mock is an object which we can set expectations on and will assert that those expectations have been
// Dynamic Mock provides easier syntax and does not require stubbing/expecting all methods

mocks.CreateMock<T>();

// Assert Was Called
mock.AssertWasCalled(p => p.Add(Arg<AnotherModel>.Is.Anything));
mock.AssertWasCalled(p => p.Add(Arg<AnotherModel>.Is.NotNull));
mock.AssertWasCalled(p => p.Add(Arg<AnotherModel>.Is.Equal(theModel)));
mock.AssertWasNotCalled(p => p.Add(Arg<AnotherModel>.Is.Null));
mock.AssertWasCalled(x => x.AReadonlyPropery);
mock.AssertWasCalled(x => x.AProperty);
mock.AssertWasCalled(x => x.AProperty = 9);
mock.AssertWasCalled(x => x.EventHandler += Arg<AnEvent>.Is.Anything); // Event was registered

// Expect & Verify
mock.Expect(p => p.Add(Arg<AnotherModel>.Is.Anything));
mock.Expect(p => p.Add(Arg<AnotherModel>.Is.NotNull));
mock.Expect(p => p.Add(Arg<AnotherModel>.Is.Equal(theModel)));
mock.Expect(x => x.AReadonlyPropery).Return(9);
mock.Expect(x => x.AProperty).Return(9);
mock.Expect(x => x.AProperty).SetPropertyAndIgnoreArgument();
mock.Expect(x => x.AProperty).SetPropertyWithArgument(11);

mock.VerifyAllExpectations()
Advertisements

HowTo – Rhino Mocks

Source Code

All source code can be found on GitHub here.

My cheat sheet in generics can be found here while some code examples in generics can be found in my post here.

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

Intro

Rhino Mocks is a mocking framework for .Net. In essence a mocking framework allows you to stub a complex expensive resource such as a database or webserver. However mocking frameworks can allow you to completely isolate a SUT during testing. Mocking frameworks also allow the creation of expectations of methods calls between a mock and the SUT; the unit test will then fail if the expected method calls were not made or made but with the wrong parameter values. Testing can then be behavioural as well as state based. This how to looks at the syntax for version 3.6 and above which does not require the record and playback syntax.

Stubs

Stub A Method

The simplest explanation of when to stub is when a resource such as a database or web service is encountered; something which is expensive to consume when unit testing. Providing a stub for a class which consumes a database can allow us to substitute this at run time making unit testing quicker and easier but also it can allow us to very easily create complex unit tests with a wealth of data which is very easy to set up without having to create test data within a database. The following simple example mocks an interface called method called Do() on interface ISimpleModel which takes no parameters and when called returns 1 as an integer. MockRepository is used to create a fake or stubbed instance of ISimpleModel, it is upon this that we are required to call our functions. If we were stubbing a class and not an interface then one thing to note is that you would not get any functionality of the class. You can not mix and match functionality of the class and stubbed functions.

var sut = MockRepository.GenerateStub();
sut.Stub(x => x.Do()).Return(1);

Stub A Property

Get functions of properties can be stubbed. The following syntax allows stubbing of a readonly property (get only).

var sut = MockRepository.GenerateStub();
sut.Stub(x => x.AReadonlyPropery).Return(1);

The following syntax allows stubbing of a get method of a property.

var sut = MockRepository.GenerateStub();
sut.AProperty = 2;  // Stubs a Get_AProperty as 2
Assert.That(sut.AProperty.Equals(2));

It is not required to stub set methods. Any methods can be consumed automatically without stubbing them, only if we need a return value other than default(T) for value types and null for reference types do you need to stub the method. Set methods return void so stubbing this is not required.

Arguments

If our stubbed methods takes arguments then we need to provide for them.

Ignoring Arguments

In the simplest form we might not care what values the parameters take and can simply state that they can be anything. Allow the argument to be Anything.

sut.Stub(x => x.Do(Arg.Is.Anything)).Return(1);

Call IgnoreArguments() will make any constrained arguments parameters have their constraints ignored.

sut.Stub(x => x.Do(Arg.Is.Equal(1))).IgnoreArguments().Return(1);

Constrained Arguments

Constrained arguments allow us to return different data based upon the method parameter values which it is called upon. When all parameters are matched the return is made. If multiple stubs are matched then the first registered stub instance is used to determine the return value.

Is

Is constants provide predicates for literal and reference types. The following is a quick run through of the Is argument constraints. Equal and NotEqual for equality based comparison.

sut.Stub(x => x.Do(Arg.Is.Equal(1))).Return(1);
sut.Stub(x => x.Do(Arg.Is.NotEqual(1))).Return(10);

Comparison between two literals.

sut.Stub(x => x.Do(Arg.Is.GreaterThanOrEqual(10))).Return(1);
sut.Stub(x => x.Do(Arg.Is.GreaterThan(10))).Return(2);
sut.Stub(x => x.Do(Arg.Is.LessThanOrEqual(10))).Return(1);
sut.Stub(x => x.Do(Arg.Is.LessThan(10))).Return(2);

Comparison to null with Is.Null and Is.NotNull.

sut.Stub(x => x.DoIFoo(Arg.Is.Null)).Return(1);
sut.Stub(x => x.DoIFoo(Arg.Is.NotNull)).Return(2);

IsTypeOf to determine if the type is of the required type. In this example Moo and Foo both implement IFoo Whig is the parameter type. Based upon whether Foo or Moo is passed in we can alter our return value.

sut.Stub(x => x.DoIFoo(Arg.Is.TypeOf)).Return(1);
sut.Stub(x => x.DoIFoo(Arg.Is.TypeOf)).Return(2);

Identity comparison with Same and NotSame functions.

sut.Stub(x => x.DoIFoo(Arg.Is.Same(foo))).Return(1);
sut.Stub(x => x.DoIFoo(Arg.Is.NotSame(foo))).Return(2);

List

The List functions allow us to provide predicates upon elements which implement IEnumerable and IEnumerable. I aliased RIS as ‘using RIS = Rhino.Mocks.Constraints.Is;’ to make a distinction between NUnit and Rhino Mocks Is. The simplest form of List is the count which allows us to compare the element count against an Is constraint. Any of the Is constraints which predicate numbers can be used; Equal IsLessThan etc. Below we stub Do(IList t) twice once for when the parameter contains no elements and another for one element.

sut.Stub(x => x.Do(Arg>.List.Count(RIS.Equal(0)))).Return(0);
sut.Stub(x => x.Do(Arg>.List.Count(RIS.Equal(1)))).Return(1);

Element allows comparison of element at a position to an Is constraint. The first parameter is the element position and the second parameter is an Is constraint.

sut.Stub(x => x.Do(Arg>.List.Element(0, RIS.Equal(1)))).Return(1);
sut.Stub(x => x.Do(Arg>.List.Element(1, RIS.GreaterThanOrEqual(2)))).Return(2);

Equal allows comparison of a collection to another.

sut.Stub(x => x.Do(Arg>.List.Equal(new int[] { 1, 2, 3 }))).Return(1);
sut.Stub(x => x.Do(Arg>.List.Equal(new int[] { 4, 5, 6 }))).Return(2);

IsIn allow predicating if an element is contained within the collection.

sut.Stub(x => x.Do(Arg>.List.IsIn(1))).Return(1);
sut.Stub(x => x.Do(Arg>.List.IsIn(4))).Return(2);

OneOf allows predicate for any elements in both collections;

if one or more elements are found in both collections then the predicate is deemed as passed.

sut.Stub(x => x.Do(Arg.List.OneOf(new int[] { 1, 2, 3 }))).Return(1);
sut.Stub(x => x.Do(Arg.List.OneOf(new int[] { 4, 5, 6 }))).Return(2);

Matches

When the predicate is more complex or the built in functionality is not sufficient the Matches function provides more scope by taking a Predicate delegate; if you can write it you can predicate it!

sut.Stub(x => x.Do(Arg.Matches(y => y > 5))).Return(1);

Repeat

It is possible to set up the stubbing for x number of repetition; thus we can return different results dependant upon the call iteration. The methods Once(), Twice() and Times(int x) are provided.

mock = MockRepository.GenerateStub();
mock.Stub(x => x.Do()).Return(1).Repeat.Once();
mock.Stub(x => x.Do()).Return(2).Repeat.Twice();
mock.Stub(x => x.Do()).Return(3).Repeat.Times(3);

ByRef and Out Parameters

By Ref parameters can be implemented by utilising the ref keyword along with the Ref and Dummy methods.

sut.Stub(x => x.Do(Arg.Is.Equal(1), ref Arg.Ref(RIS.Equal(0), 10).Dummy)).Return(1);

Out parameters can be implemented by utilising the out keyword along with the Out and Dummy methods.

sut.Stub(x => x.Do(Arg.Is.Equal(1), Arg.Is.Equal("Hello"), out Arg.Out(10).Dummy)).Return(1);

By Literal

Though highly discouraged stubbing by literals can also be utilised.

sut.Stub(x => x.Do(1).Return(1);
sut.Stub(x => x.Do("Foo").Return(2);

Mocks

A Mock is similar to a Stub, in fact it contains all the functionality mentioned above however mocks can record required behaviour and fail a unit test if the required behaviour is not called upon by the SUT. For example If we have a class A which requires to call two methods on class B with certain parameters we can ensure that all of this behaviour is called or fail the unit test. We can either place expectation calls on the mock prior to the unit test act or we can make assertions of function calls during the assert.

Assert Was Called

AssertWasCalled provides a way asserting that a function call with required parameters was called. If a return value is required then this method can not be used.

Argument Constraints

All argument constraints mentioned previously in the stubs section can and should be utilised along with the AssertWasCalled function. If the function was not called with the parameter constraints then an exception is thrown and as such the unit test fails. The following example shows how to ensure that a function is called ignoring the parameter values.

[Test]
public void WhenArgumentsIsAnything()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = "Test" };

 	modelCreator.CreateModel(theModel);

 	mock.AssertWasCalled(p => p.Add(Arg.Is.Anything));
 }

The following example shows how to ensure that a function is called ensuring that the parameter is not null.


[Test]
public void WhenArgumentsIsNotNull()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = "Test" };

 	modelCreator.CreateModel(theModel);

 	mock.AssertWasCalled(p => p.Add(Arg.Is.NotNull));

 }

The following example shows how to ensure that a function is called ensuring that the parameter is equal to a reference type.

[Test]
public void WhenArgumentsIsEqual()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = "Test" };

 	modelCreator.CreateModel(theModel);

 	mock.AssertWasCalled(p => p.Add(Arg.Is.Equal(theModel)));

 }

Assert Was Not Called

AssertWasNotCalled works exactly the same as AssertWasCalled however it throws an exception and fails the unit test if the method with argument constraints was called.

[Test]
public void WhenNotCalled()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = "Test" };

 	modelCreator.CreateModel(theModel);

 	mock.AssertWasNotCalled(p => p.Add(Arg.Is.Null));

}

Properties

The syntax for asserting that a readonly property or get method of a property is exactly the same as each other (unlike when we look at Expect and Verify!).


[Test] public void WhenReadonlyProperty()
{
	var sut = MockRepository.GenerateMock();

 	var foo = sut.AReadonlyPropery;

 	Assert.That(foo.Equals(0));

 	sut.AssertWasCalled(x => x.AReadonlyPropery);

 }

 

[Test]
public void WhenProperyGetCalled()
{
	var sut = MockRepository.GenerateMock();

 	Assert.That(sut.AProperty, Is.EqualTo(0));

 	sut.AssertWasCalled(x => x.AProperty);

 }

Asserting that a set method of a property is called with a literal value.

[Test]
public void WhenProperySetCalled()
{
	var sut = MockRepository.GenerateMock();

 	sut.AProperty = 9;

 	Assert.That(sut.AProperty, Is.EqualTo(0));

 	sut.AssertWasCalled(x => x.AProperty = 9);

 }

Expect and Verify

Expect and Verify has two advantages over the AssertWasCalled style syntax. Firstly it allows stubbing inline with the Expect function call and secondly it allows setting the expectations as part of the assign stage along with other Stub functionality which might be required. The Expect() method allows all argument constraints as shown in the stub section above and works exactly the same as stub however if when VerifyAllExpectations is called as part of the assert section of the unit test any configured expects which have not been called or called with the required parameters, an exception is thrown and the unit test fails. Unlike AssertWasCalled syntax no equivalent functionality for AssertWasNotCalled is provided.

Argument Constraints

All argument constraints are available. Below are a few examples The following example shows how to ensure that a function when it does not matter what parameters are used.

[Test]
public void WhenArgumentIsAnything()
{
	IModelRepository mock = MockRepository.GenerateMock();

	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = "Test" };

 	mock.Expect(p => p.Add(Arg.Is.Anything));

 	modelCreator.CreateModel(theModel);

 	mock.VerifyAllExpectations();

 }

The following example shows how to ensure that a function only requires that the function is called without a reference type being null.

[Test]
public void WhenArgumentIsNotNull()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = "Test" };

 	mock.Expect(p => p.Add(Arg.Is.NotNull));

 	modelCreator.CreateModel(theModel);

 	mock.VerifyAllExpectations();

 }

The following example shows how to ensure that a function with equality check for a reference type.

[Test] public void WhenArgumentIsEqualTo()
{
	IModelRepository mock = MockRepository.GenerateMock();

 	var modelCreator = new ModelCreator(mock);

 	var theModel = new AnotherModel() { FieldA = 1, FieldB = "Test" };

 	mock.Expect(p => p.Add(Arg.Is.Equal(theModel)));

 	modelCreator.CreateModel(theModel);

 	mock.VerifyAllExpectations();

 }

The following example shows how to ensure that a function is called with a number type parameter equal to 9.

[Test]
public void WhenReadonlyPropertyCalled()
{
	var sut = MockRepository.GenerateMock();

	sut.Expect(x => x.AReadonlyPropery).Return(9);

 	Assert.That(sut.AReadonlyPropery, Is.EqualTo(9));

 	sut.VerifyAllExpectations();
}

Properties

The first example shows how to place an expectation on a get method of a property.

[Test]
public void WhenPropertyGetCalled()
{
	var sut = MockRepository.GenerateMock();

 	sut.Expect(x => x.AProperty).Return(9);

 	Assert.That(sut.AProperty, Is.EqualTo(9));

 	sut.VerifyAllExpectations();

 }

This example shows how to place an expectation on a set method while ignoring the parameter value.

[Test]
public void WhenPropertySetCalledWithIgnoreArguments()
{
	var sut = MockRepository.GenerateMock();

 	sut.Expect(x => x.AProperty).SetPropertyAndIgnoreArgument();

 	sut.AProperty = 1;

 	sut.VerifyAllExpectations();

 }

This example shows how to place an expectation on a set method with an explicit value.

[Test]
public void WhenPropertySetCalledWithArguments()
{
	var sut = MockRepository.GenerateMock();

 	sut.Expect(x => x.AProperty).SetPropertyWithArgument(11);

 	sut.AProperty = 11;

 	sut.VerifyAllExpectations();
 }

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

Intro

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 – 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,

Intro

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

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);

Collection

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();
    }
}

Identity

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);

Comparision

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
             Has.InnerException.InstanceOf<ArgumentException>().And.InnerException.Message.EqualTo("Moo"));

Exception

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"); },
	Throws.Exception.InstanceOf<ArgumentException>().And.Message.EqualTo("Foo"));

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

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

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

Assert.That (() => { throw new Exception("Foo", new ArgumentException("Moo"));},
	Throws.Exception.Message.EqualTo("Foo").And.InnerException.InstanceOf<ArgumentException>());

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,

Intro

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

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

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

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

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 http://msdn.microsoft.com/en-gb/library/system.type.isassignablefrom.aspx.

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> ());

Exceptions

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 (); });

Strings

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);

//Subset
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 });

//Empty
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

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

HowTo – NUnit – Features

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,

Intro

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

The Basic Test

Any method which is decorated with the [Test] attribute which sits within a class decorated with the [TestFixture] attribute should be automatically picked up by the test runner: Resharper, NUnit-MonoDevelop etc.

[TestFixture]
public cass MyTests
{
	[Test]
	public void BasicTest()
	{
		Assert.IsTrue (true);

	}
}

The test above will pass without error as the assertion condition is satisfied; true is true. The test below fails the assertion and as such throws an exception. The test runner handles the exception marks the test as failed and continues execution of the next test; all tests will be run independently of the execution of any other tests.

[Test]
public void BasicTest()
{
	Assert.IsTrue (false);

}

TestFixture

The [TestFixture] attribute decorates a class which contains one or more tests. We can also provide a category and description to annotate our collection of tests.

[TestFixture(), Category("Example Tests"), Description("Some examples tests")]
public class Test

Ignore & Explicit

Tests can be marked as Ignored and Explicit. Both tests will not be run by the test runner though Explicit tests can be run when explicitly run; ie you run them yourself.

The provided explanation is optional and is displayed in the test runner as the reason why the test was ignored.

[Test, Explicit("Test has to be run explicitly as it does not like mondays!")]
public void ExplicitAttributeTest()
{
}

[Test, Ignore("This test is not to be run!")]
public void IgnoreAttribueTest()
{
}

Timeout & MaxTimeAttribute

Both attributes allow configuration of a max time in milliseconds.

Timeout will stop and fail a test when the test has been running for the amount of configured time.
MaxTime will fail the test once the time has been reached but the test will be aloud to complete.

[Test, MaxTimeAttribute(2000)]
public void MaxtimeAttributeTest() { }

[Test, Timeout(200)]
public void TimeOutTest() { }

Categorising Tests

The property flag can be used to categorise the test within the result output XML.

[Test, Property("ImportantTest", "Very")]
public void PropertyAttributeTest() {}

You can also define your own properties to ensure consistency. We can create an enumerator as an argument to this attribute and don’t forget you can have multiple attributes.

In the example below we define our own attribute subclassing PropertyAttribute which takes a defined enumerator. We the decorate a the test with this attribute and an enum value.


[AttributeUsage(AttributeTargets.Method, AllowMultiple = false)]
public class CustomPropertyAttribute : PropertyAttribute
{
	public CustomPropertyAttribute( CustomPropertyValue value ) : base( "Custom", value.ToString() )
	{
	}
}

public enum CustomPropertyValue
{
	One,
	Two,
}

[Test, CustomPropertyAttribute(CustomPropertyValue.One)]
public void CustomPropertyAttributeTest() {}

SetUp & TearDown

[TestFixtureSetUp] marks a method which is called once prior to all unit tests whiting a [TestFixture] class. No matter how many [Test]’s are found whiting the test fixture the method is called only once. It provides a common point for placing code required to set up the test fixture.

TestFixtureSetUp does not promote proper test isolation. Initiating code common between unit tests should be used lightly and only when required. We don’t want one unit test failure to bring down other unit tests nor do we want a required order for unit tests. It is preferred to take the performance hit for initiating required classes for each unit test. Trying to find out why numerous unit tests have failed instead of one is a lot more work to do! XUnit has no such feature and only provide a test set up to promote correct test isolation. Some people actually prefer one test per source file.

If a [TestFixtureSetup] method throws an exception then no tests within it are run.

[SetUp] marks a method which is called before every test in the test fixture. If a test fixture contains 100 tests, this method is called 100 times. If the method throws an error no tests in the test fixture are run.

[TearDown] marks a method which is called after every test in the test fixture. If a test fixutre contains 100 tests, this method is called 100 times.

[TestFixtureTearDown] marks a method which is called once after all tests within a test fixture have been run. If a [TearDown] has been provided [TestFixtureTearDown] will be run after the last call to [TearDown]

[TestFixtureSetUp] public void FixtureSetUp() { }

[TestFixtureTearDown] public void FixtureTearDown() { }

[SetUp] public void SetUp() { }

[TearDown] public void TearDown() { }

SetUpFixture

The [TestFixtureSetUp] attribute marks a config class for providing a test fixture. It provides with [SetUp] and [TearDown] methods; you can have a maximum of one of each type. The class is required to be public and have a parameter-less constructor.

[SetUp] will be called once before any test fixtures tests, [SetUp] [TestFixtureSetUp] methods are called.
[TearDown] will be called after all tests, [TearDown] and [TestFixture] methods are called.

The methods will be called at most once each irrelevant of how many test fixtures it will be used for.

[SetUpFixture]
public class TestFixtureSetUp
{
    [SetUp]
	public void RunBeforeAnyTests() { }

    [TearDown]
	public void RunAfterAnyTests() { }
}

TestCase

The TestCase attribute provides a way of specifying a test’s methods parameter and required return value or result. This allows one test to be called with a varied range of test values.

In our example method it takes takes two integers and returns an integer though any amount or types of parameters and return results can be used. You simply need to ensure that the number of types match.

[TestCase(1,1, Result=2)] defines that the method will be called with parameters a and b with a value of 1 and test iteration will only pass if the return value is 2.

[TestCase(1,1, Result=2)]
[TestCase(2,2, Result=4)]
[TestCase(3,3, Result=6)]
public int TestCaseTest(int a, int b)
{
  return( a + b);
}

Range

The Range attribute allows us to define a list of possible values which are passed each time into a parameter of our test method. This is done by specifying a min, max and increment.

The following example has a [Range(0.0, 1, 0.5)]. The test method will be called with values of 0, 0,5 and 1.

[Test]
public void RangeAttributeTest(
[Range(0.0, 1, 0.5)] decimal value) { }

Random

The Random attribute allows the function to be called x times with a random value between a specified min and max.

The example below has Random(1, 10, 2)] int value: The method will be called twice with a value equal to or between 1 and 10.

[Test]
public void RandomAttributeTest(
[Random(1, 10, 2)] int value) { }

Sequential

The sequential attribute allows us to define a range of values for each parameter. The sequential attribute decorates the Test while the Value attribute decorates each parameter.

Our method takes an int x and a string s:

[Values(1,2,3)] int x: means x will be set to 1, 2 and then 3.
[Values(“A”,”B”)] string s: means that s will be set to “A” and “B” and null.

Because x has three defined values and s will have two, s will be called the final time with null or the default(T) value; if s was an int 0 would be specified as the last called value.

To clarify our parameter pairs will be run with: {1,A}, {2,B}, {3, null}

[Test, Sequential]
public void SequentialAttributeTest(
[Values(1,2,3)] int x,
[Values("A","B")] string s) { }

The combinatorial allows us to specify a combination of values for each parameter.

By specifying the first parameter as having [Values(1,2,3)] and the second parameter as having Values(“a”, “b”, “c”)]; the first parameter will be 1,2 or 3, the second parameter will be “a”, “b”, or “c”. The method will be called once with every possible combination of parameters defined. In this case it will be 9 times: {1,a}, {1,b}, {1,c}, {2,a}, {2,b}…. {3,c}.

[Test, Combinatorial]
public void CombinatorialAttributeTest ([Values(1,2,3)] int a, [Values("a", "b", "c")] string b) { }

TestCaseSource: Public Property

TestCaseSource allows us to provide test data for a function by defining a public property which returns an array of arrays. Each internal array is a defined set of parameter values for a test iteration.

In the example below the public property CaseSourceTestData defines our parameters to be used. We then tell our test to use this as our parameters source be passing the name of the property as a string into the TestCaseSource attribute: [Test, TestCaseSource(“CaseSourceTestData”)].

Any number of parameters and types can be used along as they match the method signature.

public static object[] CaseSourceTestData =
{
    new object[] { 1, 1.1m, "2.1" },
	new object[] { 2, 2.2m, "4.2" },
	new object[] { 3, 3.3m, "6.3" },
};

[Test, TestCaseSource("CaseSourceTestData")]
public void CaseSourceTest(int a, decimal b, string c) { }

TestCaseSource can also be defined by providing a factory class and the name of a public property which returns IEnumerable.

The yield keyword is used to return a test iterations parameter values.

Each iteration requires to return an instance of TestCastData initiated with a value for each parameter in the test method.

yield return new TestCaseData( 1, "1" );

TestCastData has fluent syntax and be used to define a require return result

yield return new TestCaseData( 1, "1" ).Returns( 2 );

or expected exception to be throw

yield return new TestCaseData( 0, "a" ).Throws(typeof(ArgumentException));

The test is configured to use the factory class and property which returns the above information by:

[Test,TestCaseSource(typeof(TestCaseDataFactory),"TestCasesDataForTestCaseSourceTest")]

In this example the class TestCaseDataFactory is our provider class and TestCasesDataForTestCaseSourceTest is the name of the property which has out test data.

The has to be public and static or the class has to have a paramaterless constructor.

In the following example our method takes an int, a string and returns a decimal. The test is called three times:

(1,”1″) with expected result 1
(2,”2″) with expected result 2
(0,”a”) with expected result of an ArgumentException being thrown.

[Test,TestCaseSource(typeof(TestCaseDataFactory),"TestCasesDataForTestCaseSourceTest")]
public decimal TestCaseSourceTest(int a, string b)
{
	int bInt;
	if( !int.TryParse(b, out bInt))
		throw new ArgumentException(string.Format("Can not parse '{0}' to an integer", b), "b");

	return a + bInt;
}

public class TestCaseDataFactory
{
  	public static IEnumerable TestCasesDataForTestCaseSourceTest
	{
	    get
	    {
	      yield return new TestCaseData( 1, "1" ).Returns( 2 ); // Defines the test data and the expected return
	      yield return new TestCaseData( 2, "2" ).Returns( 4 );
	      yield return new TestCaseData( 0, "a" )
					.Throws(typeof(ArgumentException)); // Defines the test data and the expected throw exception
	    }
	}
}

Exceptions

Unit testing requires testing “The Good, The Bad and the Ugly”. Exceptions are valid results when we are expecting them. If our test throws an expected exception we can cater for a passing test. We can even specify the type of exception and the internal message.

See the next post for expecting exceptions with assertions; this covers only the attribute decorations.

The internal message can be asserted with a few different techniques via an enum.

MessageMatch.Contains: The inner messages contains the ExcpectedMessage anywhere within the string (like ‘%Foo%’).
MessageMatch.Exact: The inner message matches the ExpectedMessage exact ( = ‘Foo’ ).
MessageMatch.StartsWith: The inner message starts with the ExpectedMessage ( like ‘Foo%’ ).
MessageMatch.Regex: The ExpectedMessage is a regular expression which describes the inner message.

The ExpectedMessage is optional.

[Test, ExpectedException( typeof(Exception), ExpectedMessage = "Foo", MatchType = MessageMatch.Exact)]
public void ExpectedExceptionAttributeTest()
{
	throw new Exception("Foo");
}