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

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

Intro

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

	[Fact]
	public void SimpleExample()
	{
	    Assert.True(true);
	}

	public void Dispose()
	{
	}

}

IUseFixture

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

	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}

[Theory,
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);
}

PropertyData

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
{
    get
    {
        yield return new object[] { 1, true };
        yield return new object[] { 2, true };
        yield return new object[] { 3, false };
    }
}

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

Assertions

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.

Assert.False(false);
Assert.NotNull(false);
Assert.Null(null);
Assert.True(true);

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,

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