Comparing mocking frameworks: How to handle optional parameter with NSubstituite, Moq and FakeItEasy

Comparing mocking frameworks: How to handle optional parameter with NSubstituite, Moq and FakeItEasy

Depending on which mocking framework you are using you might have to handle optional parameters differently and in this short article I will compare and demonstrate the differences in the three major mocking frameworks NSubstitute, Moq and FakeItEasy.

Let's assume that we have a service with an interface called ISomeService and a method called SomeMethod which has one required parameter and one optional one:

In NSubstitute you actually don’t have to do anything special to work with optional parameters. Simply reference the method without using the optional parameter and set a return value of your choice and the framework will handle everything for you:

Unfortunately, it’s not this straightforward in Moq and FakeItEasy. If we take a somewhat similar approach in these frameworks and try to set a return value without referencing the optional parameter we will get a compilation error saying:

-“An expression tree may not contain a call or invocation that uses optional arguments”.

This is not actually an issue with the mocking frameworks but rather the underlying expression tree API that doesn't support optional arguments and as you can see the same goes for FakeItEasy and so it becomes a problem because of the nature of these two frameworks.

To fix this we have to provide the call with a default value that is not important for us but needed to make our test code compile. In Moq this can look something like this (there's probably a ton of other ways but this works):

And somewhat similar but slightly different in FakeItEasy:

Using these two approaches our code now compiles and we get the same green output from all the three frameworks.

So as you can see in this specific case point goes to NSubstitute for a much more straighforward approach. But as always when comparing frameworks there's going to be some specific things that one frameworks does better than others and vice versa. (I've planned on doing a head-to-head comparing mocking frameworks article similar to my NUnit vs xUnit article, stay tuned..)

Source code from this article can be found here.

Cheers friends! ❤️