Thoughts, Tips and Tricks on what I'm currently do for a living. Currently most of my spare time is spent on contributing to Akka.NET.

Wednesday, March 9, 2011

An extension method for creating a strict mock in FakeItEasy

The FakeItEasy framework prefers that you don’t create strict mocks, but whenever you need one this extension method might come in handy.

/// <summary>Creates a strict mock of type <typeparamref name="T"/>.</summary>
/// <typeparam name="T">The type of the object to fake.</typeparam>
/// <returns>A FakeItEasy fake configured to behave as a strict mock.</returns>
public static T Mock<T>()
{
  var fake = A.Fake<T>();
  Any.CallTo(fake).Throws(new Exception(string.Format("An unexpected method was called on the fake object {0}.", typeof(T))));
  return fake;
}

To create a strict mock:

var foo = AStrict.Mock<IFoo>();

After you have configured your mock in this fashion you can configure any "allowed" calls as usual, for example:

A.CallTo(() => foo.Bar()).Returns("bar");

 

Example and code based on: http://code.google.com/p/fakeiteasy/wiki/StrictMocks