Don’t be confused, the title is just to get your attention. This is not a benchmark between Mockito and Moq. I need to  explain some differences to my teammates so that the transition between Mockito and Moq is softer for them.

Typical way to stub out a method call with mockito:

when(colaborator.method(argument1)).thenReturn(whateverIwant);

Same with Moq:

colaborator.Setup(x => x.method(argument1)).Returns(whateverIwant);

Obviously, the mockito way is nicer. I believe this is because of Java capabilities but I am not sure. I would like to dig into mockito’s source code to see how is this possible. I will do it and blog about it soon. I used to think that it was because of the kind ot late binding supported by Java, but I am not sure.

Moq uses a lambda expression (anonymous method inlined) to tell the framework which method and how is expected to be called). The reason I use “x” for the object in the anonymous method is because it refers to “colaborator” itself so there is no point in adding more names.

The other important difference relates to the “virtual” keyword in C#. Methods in C# are final by default. You can’t override them unless they contain the keyword “virtual” on its signature. Both, Mockito and Moq create test doubles by subclassing on runtime, overriding methods and implementing the fake behavior on them (as far as I know). So, if the method you want to stub is not virtual, Moq will throw a runtime exception. If it is not virtual but you don’t specify any fake behavior on it, it will not throw exceptions, but worse, it will call the actual implementation. So you might be hiting the database in your unit tests inadvertedly. What I do, is that all my methods are virtual by default (I write “virtual” on their signature).

There will be more posts on this topic 🙂