Mocking Frameworks in .Net

As a contractor I have seen a lot of different companies’ code bases and been on many different projects. Most companies now employ TDD (which is a good thing). This means that often you need a mocking framework. Mocking frameworks are ten to the dozen and I have used many different ones over the years.

The most common mocking framework in .Net that I have come across by far is Moq. I quite like Moq but the syntax is a bit clunky. For example to setup a mock repository to return a fake customer:

 var mockRepository = new Mock();
 mockRepository.Setup(m => m.GetCustomer(It.IsAny()).Returns(new Customer{ Id = 1234, Name = "Fred" });
 var customerController = new CustomerController(mockRepository.Object);

What I don’t like is that the variable mockRepository is not an ICustomerRepository it is a Mock<ICustomerRepository>. The Mock is a wrapper around your type. This means that when you inject your mock into the class you are testing you need to use the .Object property as can be seen on line 3 above.

Compare this to FakeItEasy:

 var mockRepository = A.Fake();
 A.CallTo(m =&gt; m.GetCustomer(A.Ignored).Returns(new Customer{ Id = 1234, Name = "Fred" });
 var customerController = new CustomerController(mockRepository);

This feels so much cleaner to me because this time mockRepository variable is a ICustomerRepository. The A.Fake<T>() method is a factory method from the FakeItEasy library that does some clever work with a dynamic proxy to fill the provided interface (in this case ICustomerRepository) on the fly. This also means that when we pass the mock into our CustomerController this time we just pass mockRepository, we don’t need to use the .Object extension which feels much cleaner (see line 3 in the 2nd snippet above).

Which mocking frameworks have you used? What are the pros/cons?