Moq vs. NSubstitute vs. FakeItEasy

Today I though I would do some syntax comparison between a few of the biggest Mocking Framework in .NET:

Moq, NSubstitute and FakeItEasy.

Although these framework have slight functional differences (some of which I've already mentioned in previous post) they pretty much do the same thing but in different syntax and lingo.

Just as when you're choosing a test framework, choosing the right mocking framework for you and your team is usually a matter of personal preferences and taste.

Therefor I though I would list a few common mocking operations and how you perform these in these three frameworks and let you decide for yourself which one you prefer.

Alternatively you could also use this as a reference when switching between projects that use different frameworks to translate from one to the other.

I will try to keep this page updated once I come up with new operations. Consider this a work in progress. Hope it may help someone.

Cheers friends! ❤️

Create Mock / Substitute / Fake

Moq:

var service = new Mock<ISomeService>();

You can also specify if your mock should be loose or strict, which I've covered in this article. Alternatively if you only need the mock object and not plan on doing any setups you can use:

var serviceObject = Mock.Of<ISomeService>();

NSubstitute:

var service = Substitute.For<ISomeService>();

FakeItEasy:

var service = A.Fake<ISomeService>();


Returning values

Moq:

service.Setup(x => x.SomeMethod("something")).Returns("any");

NSubstitute:

service.SomeMethod("something").Returns("any");

FakeItEasy:

A.CallTo(() => service.SomeMethod("something")).Returns("any");


Throwing exceptions

Moq:

service.Setup(x => x.SomeMethod(null)).Throws<Exception>();

NSubstitute:

service.SomeMethod(null).Throws(new Exception());

FakeItEasy:

A.CallTo(() => service.SomeMethod(null)).Throws<Exception>();


Verify
Received
MustHaveHappened

Moq:

service.Verify(x => x.SomeMethod("something"));

NSubstitute:

service.Received().SomeMethod("something");

FakeItEasy:

A.CallTo(() => service.SomeMethod("something")).MustHaveHappened();


VerifyNever
DidNotReceive
MustNotHaveHappened

Moq:

service.Verify(x => x.SomeMethod("never"), Moq.Times.Never());

NSubstitute:

service.DidNotReceive().SomeMethod("never");

FakeItEasy:

A.CallTo(() => service.SomeMethod("never")).MustNotHaveHappened();