Easy Mocking With FakeItEasy

While there are already plenty of good mocking frameworks available for .NET, two more frameworks have been recently released and I figured I’d do a quick overview on both. First I’ll cover FakeItEasy, and in my next post I’ll take a look at NSubstitute. The first is FakeItEasy, a framework “designed for ease of use and for compatibility with both C# and VB.NET”. Sounds good right? It even got a lofty endorsement from Roy Osherove, author of The Art of Unit Testing, who said “it’s a no brainer – FakeItEasy is the new Moq.” That is a big claim given how simple Moq is to use and read.

Prove it

Fair enough, let’s do a couple quick examples and see it in action. First you need to download the latest version and reference the FakeItEasy.dll in your project. Next we’ll do a quick test on some contrived code from an ASP.NET MVC project. Say we have a controller that handles a contact portion of our site and we want to test that when a valid message is provided, that it is submitted. Given something like this:

We could write a quick test using FakeItEasy’s syntax like such:

Pretty simple, huh? The syntax is nice. I find it a little easier to read than Moq’s, but no major differences.

Another Example

Let’s test some more useless, made up code. This time we’ll mock something that returns a value. The object we are mocking returns a boolean value, and in our test we’d like to simulate it returning false:

Summary

There is no doubt that FakeItEasy is easy to use, and the syntax is nice, but is there a big enough difference to warrant switching mocking frameworks? I can’t really answer that for you. Personally I use Moq, and have mostly enjoyed using it so far. So I’m not about to swap frameworks just yet, but I will keep an eye on FakeItEasy. I would recommend giving it a shot and seeing what you think of it. Perhaps run it by your team and get their thoughts on it. You might find the nicer syntax improves testing and readability enough to be worth switching.

Comments