share
Stack OverflowWhat C# mocking framework to use?
[+499] [20] Corin Blaikie
[2008-09-01 01:57:02]
[ c# .net unit-testing mocking ]
[ http://stackoverflow.com/questions/37359/what-c-mocking-framework-to-use ] [DELETED]

I want to start using mock objects [1] on my next C# project.

After a quick Google search I've found there are many:

So my question is: what one is your favourite .NET mocking framework and why?

[+284] [2008-09-01 01:59:05] Matt Hamilton [ACCEPTED]

I've not used most of the ones you've listed, so I can't be objective about it, but I use Moq [1] and it has been awesome. The fluent interface makes it a joy to work with. For example:

mockService.Setup(s => s.GetCustomers()).Returns(new List<Customer>());

@Ngu Soon Hui, I wasn't aware that the other frameworks don't have compile-time checking. Moq certainly does. In my example above, if the service class that mockService is mocking doesn't have a GetCustomers() method, I would get a compile-time error. I'd also get one if the GetCustomers() method didn't return a List<Customer> or an interface like IList<Customer>.

[1] http://code.google.com/p/moq/

C# 3.0, nemo, which means .NET 3.5 or above. - Matt Hamilton
I dislike Moq cause everything is a Mock there. Mock is supposed to be one per test. - Arnis L.
(9) Huh? "Everything is a Mock"? I mock only the things that support the object I'm testing, nothing more. - Matt Hamilton
(14) Another vote for Moq. Fluent interface, pretty extensive compile-time checking, intellisense Just Works; it's great. I strongly suggest you use the latest trunk version; the binaries on the website were missing some fixes that I really needed, like support for larger argument counts among other things. One big Moq downside is the docs lag behind the implementation, but if you invest the time to learn how it actually works, it pays dividends almost immediately. - anelson
(4) @Arnis L. - "Mock is supposed to be one per test" - what do you mean by this? If I am testing an object which has two external dependencies which I need to mock out, what am I supposed to do? In this case I clearly need two mocked objects. - Adam Ralph
@AdamRalph that's what Osherov wrote in his 'Art of unit testing' book. Mock is a fake instance that we verify against where stub is just a fake instance that helps to get things up and running (mock kind a inherits stub, is a bit advanced). In your case - your external dependencies likely would be just a stubs. Moq framework blurs this line and there's just a Mock and no stubs. Lack of dividing responsibilities where i believe it shouldn't be taken away. That's all. :) - Arnis L.
One thing I has some trouble finding it checking that a method is called with someagument (whataver arguments). It's done like this: myMock.Verify(foo => foo.MyMethod(It.IsAny<string>(), It.IsAny<int>(), Times.AtLeastOnce()) for a method MyMethod(string, int). - Wernight
I like and use Moq, but looking at its google code page recently, I realized that as of now, there was no activity in the source code since Aug. 2010. Based on that, I would not choose Moq again. - Christoph
(5) @Christoph that's because Kzu moved to Codeplex. There are check-ins from March this year. moq.codeplex.com - Matt Hamilton
I use Moq a lot, the most annoying thing I found with this framework is that mocked contructors are not checked at compile time. All other method have compile time validation but not constructor. - Vincent Hubert
(1) @MattHamilton on that page it still says that the migration to codeplex is 'in progress' and they still recommend to download via the google code link. - dodgy_coder
(1) I'm using Moq with a C# 4.0 project and its working really well. Thanks for this answer. - dodgy_coder
(2) I'm using Moq too and I'm quite happy with it. But you have to know that it brings some limitations. You can mock only interfaces and abstract classes but no regilar (non-abstract) classes. You also cannot mock mathods using a large number of parameters (I think more than 4 or so). - llasarov
(8) be aware that the Rhino Mocks project is DONE. Do not use it bit.ly/11qGv7L - CoffeeAddict
(2) @ Adam Ralph PER YOUR "what do you mean by this? If I am testing an object which has two external dependencies which I need to mock out, what am I supposed to do?" It means you're not doing true TDD because if you were, your tests would be so small, there would only be a need for just ONE mock PER TEST. If you have this debate with your code then you are NOT doing true test driven development or you wouldn't even be questioning the best practice of one mock per test. Your tests are too long and/or doing too much is my point. - CoffeeAddict
(2) @CoffeeAddict But what if he calls the tests "integration tests" instead. Is it okay then, or are we not allowed to use mocking frameworks for integration tests? True TDD is fine in theory. Real life is a bit more complex. - Nilzor
@CoffeeAddict you're making an assumption that he is doing (or trying to do) TDD... while certainly a superior way to code in almost all circumstances, there are many cases where that is simply not the case, and often even for good reason. - Jeremy Holovacs
As of 2014 the main Moq repo is now at GitHub github.com/Moq/moq4 and it's also available from Nuget nuget.org/packages/Moq - Ian Kemp
1
[+63] [2010-04-13 14:31:28] Patrik Hägne

I used Rhino.Mocks before and it's certainly a good product. However there were some painpoints for me and I don't like the Moq-style where you have "Mock-object". To scratch this itch I created my own "fake-framework" called FakeItEasy. Now almost a year later it's a pretty mature project that's used in large scale production systems.

// Creating a fake object is just dead easy!
// No mocks, no stubs, everything's a fake!
var lollipop = A.Fake<ICandy>();
var shop = A.Fake<ICandyShop>();

// To set up a call to return a value is also simple:
A.CallTo(() => shop.GetTopSellingCandy()).Returns(lollipop);

// Use your fake as you would an actual instance of the faked type.
var developer = new SweetTooth();
developer.BuyTastiestCandy(shop);

// Asserting uses the exact same syntax as when configuring calls,
// no need to teach yourself another syntax.
A.CallTo(() => shop.BuyCandy(lollipop)).MustHaveHappened();

Check it out at fakeiteasy.github.io [1]

[1] http://fakeiteasy.github.io/

(1) Great job, Patrik! It's been a joy to use FakeItEasy. - Igor Pashchuk
FakeItEasy rocks! Thanks Patrik! - Sam Pearson
+1 - I used Moq (current top-rated answer) before I used FakeItEasy, and I like FakeItEasy better. - Tim Lovell-Smith
2
[+49] [2008-09-01 02:54:06] jfs

Roy Osherove has a poll about it on " Choosing a Mock Object Framework [1]". Some frameworks that you have not listed:

Top 3 frameworks from the poll are:

  1. Rhino Mocks
  2. TypeMock
  3. NMock

Unfortunately, Moq is not among the choices. But maybe this post will help " Why do we need yet another NET mocking framework? [4]" (this is about Moq)

[1] http://www.osherove.com/blog/2007/4/26/choosing-a-mock-object-framework.html
[2] http://nunit.org/
[3] http://nmock.org/index.html
[4] http://www.clariusconsulting.net/blogs/kzu/archive/2008/03/17/WhydoweneedyetanotherNETmockingframework.aspx

(21) Moq won Roy's latest poll: polldaddy.com/poll/3746444 - TrueWill
(1) A post from Charlie at NUnit saying its NUnit.Mocks framework is a "toy" - groups.google.com/group/nunit-discuss/msg/55f5e59094e536dc Rude awakening to some: "I'm beginning to think that [NUnit Mocks] was a mistake, because you are far from the first person to become reliant on it." - John K
3
[+42] [2010-08-20 19:36:12] HaraldV

I assume you have choosen your framework by now, but hopefully this post will help others to choose what's right for them!

I've used Moq and was mostly happy with that. The syntax makes tests pretty readable. However Roy Osherove introduced me to FakeItEasy [1], and I find that even more fluent and easy to use than Moq.

You should choose a mocking framework based on your needs. If you are planning to do your system from scratch, you should design it for testing and then one of the free frameworks would be more than sufficient! I can't come up with any reason for myself changing to a commercial mocking framework.

I would however like to mention that there are some very important differences between the mocking frameworks. Some are proxy based, like Moq, FakeItEasy and Rhino Mocks. Your fakes will be created on the fly, implementing or overriding the classes/interfaces. You have to stick to the rules of inheritance, so you can't just hook into a method that doesn't support overriding or are defined in an interface. They kind of force you to create testable code.

Justmock and Typemock are profiler based, meaning that they can intercept calls to any method to assert that it has been called, changing its return value, etc. If you, for example, have a legacy system or you depend on another commercial system like SharePoint and want to write tests, one of the commercial frameworks might do the trick.. Say you have dependencies to static classes like DateTime.Now, Random or something home grown. These frameworks will make it possible for you to intercept the calls and return your own values! If you are using a proxy based framework, you must design/refactor your code to get past such dependencies (for example, extract and override).

Good luck!

[1] http://code.google.com/p/fakeiteasy/

@Peter Mortensen: I'm needing to mock static classes like you mentioned but can't figure out how to do it and can't find a Google resource. Do you have any tips or resources you can recommend? - gabe
Take a look at Microsoft moles. I used it in a project and it worked pretty well for me. here's the link: research.microsoft.com/en-us/projects/pex/downloads.aspx - Buzzer
4
[+33] [2010-08-29 07:56:33] CAD bloke

Have a look at NSubstitute [1]. Also, here is a series of blog posts [2] comparing some of the major players, including NSubstitute.

[1] http://nsubstitute.github.com/
[2] http://www.richard-banks.org/search/label/mocking

5
[+25] [2008-09-01 03:09:05] akmad

Another vote for Rhino Mocks here. My reasons are simple:

  1. It's free
  2. It's open source
  3. It's easy to use.
  4. The syntax is great (logical and consistent).

I tried NMock and TypeMock and found both lacking.


[Personal Opinion] It's also a bit too much to get started... I checked it out.. i guess last year and found the learning curve steep and the syntax non-intuitive. - Gishu
(3) Agreed. I'm looking at switching to Moq. There is no way I can get buy-in from all 10 of my developers if they have to go through what I've gone through to even scratch the surface of Rhino. - womp
(12) Rhino Mocks is good, but ... logical and consistent? It's evolved to the point where there's sometimes 3 ways to do any one thing! I like it a lot, but there's a lot of room for improvement in the API. - Mark Simpson
I can't comment on the different mocking styles that have been added, I just use the standard style and find it sufficient (as well as logical and consistent ;)) for all my needs. However, with the additional styles that have been added I can see your point. That said, if I were just learning mocking in .Net I would go with Moq. - akmad
(1) +1 I don't agree Rhino Mocks is easy or consistent, however it's not lacking and that's why I'm using it. I had to dump moq because of its lack of support for out/ref params (yes, there is a trick to make it do those but only kind of when you get into the details), and NUnit Mocks is just a toy implementation. - John K
6
[+16] [2008-09-01 05:19:16] Rob Bazinet

Are you on .NET 3.5? If you are then consider Moq [1], it is a full-featured mocking framework some some really nice features.

If not on .NET 3.5 then I would go with Rhino Mocks. They have a huge community following so the answers to your questions should be easily available.

[1] http://code.google.com/p/moq/

7
[+13] [2008-09-01 02:07:04] Toran Billups

Rhino Mocks

  • Oren is a genius
  • Open Source

If you need to test a ton of legacy code, you might look into TypeMock as it can mock just about anything known to man ;)

For more information, checkout this post [1] by Roy Osherove

[1] http://weblogs.asp.net/rosherove/archive/2007/04/26/choosing-a-mock-object-framework.aspx

(1) You should also check if Moles from Microsoft can help you if you have legacy code. - Piotr Owsiak
8
[+11] [2011-06-29 21:39:03] harvest316

I just discovered NSubstitute, and for a rusty old programmer like myself, NSubstitute is a total God-send! After messing about with Rhino Mocks for ages, I kept on hitting all sorts of obscure roadblocks, like being unable to mock .ToString(), but NSubstitute just works. Plug and play, buddy. Hooray for well-designed software!


9
[+9] [2008-09-01 02:14:37] Graviton

Typemock [1]. It's the only mocking framework that allows you to check your mocking calls in compile time ( You can use natural mock for that purpose).

The only thing is it is not free for commercial development.

Edit: A bit of shameless plug, here's an article [2] I wrote on unit testing ASP.NET MVC using Typemock AAA syntax.

[1] http://www.typemock.com
[2] http://www.typemock.com/Unit_Testing_ASP_NET_MVC_tutorial.php

(14) Wrong. Moq supports compile time checking. - Finglas
10
[+8] [2009-07-03 12:26:14] Michaël Larouche

I prefer Moq [1] when I develop with .NET 3.5. Very nice use of the lambda expressions. Otherwise I think I'll use RhinoMocks on a .NET 2.0 only project

[1] http://code.google.com/p/moq/

11
[+6] [2009-04-07 14:16:12] Mo-Typemock

Disclaimer, I work for Typemock.

Mr Rogers – A good resource for ASP.NET unit testing (that doesn't use Rhino.) As an example: http://www.typemock.com/ASP.NET_unit_testing_page.php


12
[+5] [2012-02-27 18:42:27] Boris

Another alternitive is JustMock from Telerik. They have free and commercial versions. I was using free version for one of my projects and very happy with the results - quick and easy.


i dont think they have the free version for just mock any more the site only offers a 30 day trial now - Chris McGrath
free version is still available - it's in NuGet now. There's a link to it in the small text at the bottom of their web pages - Shevek
13
[+4] [2009-12-07 18:22:59] mikwal

An alternitive with intuitive and easy to learn syntax is http://simpledotnet.codeplex.com/


14
[+4] [2010-03-08 06:23:04] user127954

I'm in charge of deciding on which mocking framework to use in my company. I've used both Moq and Rhino Mocks and so far I'm digging Moq. Some of our developers get confused by lambda expressions, but I think once you get used to them Moq is awesome. Rhino "seems" a little bit more powerful so far, but I prefer the fluent interface on Moq. I also think the record type syntax would confuse everyone more than the more concise lambda expressions.

On another interesting note it looks like we have a "NMock3" that's now in beta: http://nmock3.codeplex.com/


15
[+4] [2010-04-09 15:22:03] Bas

I'm currently unit testing with Moq, and I must say it works pretty well! - rephrase: It works great! I've not used any of the other mocking frameworks you mention, so I can't give you a comparison. But I can say that I'm glad that I've chosen Moq as my first-to-try mocking framework. The lamda expressions are really nice and it's also pretty lightweight and reader friendly (the record/replay syntax in most other mocking frameworks aren't really doing your readability any good).

Besides that (and this is a bit off-topic) I will be using Ninject [1] in the near future as the IoC [2] container, and both frameworks go hand-in-hand. Ninject also has lambdas and it even provides auto-mocking container support for Moq (using an extension). So if you're also planning to use an IoC container you could check this awesome combination.

[1] http://ninject.org/
[2] http://en.wikipedia.org/wiki/Inversion_of_control

16
[+4] [2011-05-18 03:32:59] Steve

Seriously consider looking at "Moles", Microsoft's offering for mocking. It has by far the best syntax (mocking a method is simply supplying a delegate to a stub class, much nicer that other frameworks). It also supports mocking static methods, sealed classes, constructors, etc., without having to change any source code whatsoever (i.e. you don't need to program to an interface to mock out objects and methods). It can mock any object, including objects in the .NET framework. Imaging mocking DateTime.Now without have pre-planned in your code to do so. And it is free.


(1) Looks like Moles is becoming Microsoft Fakes in VS 2012. See this post. - TrueWill
(2) And worst of all, not free anymore. - CSharpenter
trash, it's verbose, based on xml, it has no behavioral validation. It's junk. - CoffeeAddict
and you shouldn't be wanting to mock a lot of static classes anyway. You should ask the question instead of if your code smells. Having too much static is bad. It's a sign of code smell so the argument that you want to mock a lot of static classes means you're not building a very good architecture to begin with. - CoffeeAddict
17
[+2] [2008-09-01 04:05:33] Mr Rogers

I've had the same question as Corin because I've wanted to get more into test driven development. It seems like most of the examples for ASP.NET MVC that I found had Rhino Mocks examples. However, most of my test driven development has been with Ruby on Rails and Moq has really appealed to me. I love the simplicity and forward thinking design. It's definitely one I plan on trying.


18
[+2] [2012-06-03 18:51:34] Saleh Rahimzadeh

I test many Mock frameworks, i found Telerik JustMock is very good and easy, it is a very professional and full-featured mocking framework, and also with a comprehensive document.


19
[+2] [2012-12-04 23:13:17] Dave Clemmer

I have found Simple.Mocking [1] to be an easy framework to use (easy to fake interfaces, delegates, etc.). It's free and open source.

[1] http://simplemocking.codeplex.com/

20