Mocking Frameworks for C #

I am new to ridicule, so I may have it completely wrong, but I believe that most mocking frameworks are interface dependent. Unfortunately, most of our code does not use an interface. Now, the other day, I saw a Java Mocking framework that played back the bytecode of a class \ object so as not to call its internal methods, but you can still verify that it calls these methods.

My question is: Does .Net have any mocking frameworks that can do such a thing? I'm looking for something free, and I don't want what requires methods to be virtual or abstract.

+14
c # mocking
Jul 12 '10 at 16:24
source share
4 answers

Microsoft Research developed Moles for this, which is part of Pex, but can be installed independently. And it's free. The website has a good introductory article (pdf) that explains how to mock the static method. It will take some time before they get to the material you need (page 16, task 3).

Here and here (channel 9) you can find an example on how to stub DateTime.Now . Using Moles, you can make fun of everything you want.

+10
Jul 20 '10 at 19:33
source share
— -

TypeMock Isolator can make fun of any .NET class, but it's not free (or cheap, even). I'm not sure how it works exactly, but it achieves the same end result.

But most of the mocking frameworks are not dependent solely on interfaces; they should also be able to handle specific classes, although they can only redefine virtual or abstract methods.

+8
Jul 12 '10 at 16:26
source share

You can use classes instead of interfaces with Moq and Rhino.Mocks , but the mocking methods must be virtual. Mark Rushakoff's answer to TypeMock is correct (+1).

The best option is to reorganize existing code for verification (which may take some time). I would recommend reading Effectively work with obsolete code from Michael Feathers.

+6
Jul 12 '10 at 16:33
source share

Many .NET frameworks use Dynamic Proxy Lock to create mocks at runtime. Therefore, the restriction of only allowing the interface / virtual methods to mock comes from Castle, and I think it is embedded in the CLR. Both MOQ and RhinoMocks can mock virtual methods that are just as good as them.

Both classes and interfaces can be proxies, but only virtual participants can be intercepted.

My advice would be to start creating abstract bases for those classes that should be mocked and have a specific class. Then the abstract base can be circumvented and ridiculed. This is really refactoring that is not too complicated.

+1
Jul 26 '10 at 8:33
source share



All Articles