tags:

views:

187

answers:

4

I am new to mocking so I might have it totally wrong here but I believe that most mocking frameworks are interface dependent. Unfortunately most of our code is not using an interface. Now the other day I saw a Mocking framework in Java that reproduced the byte code of a class\object as to not call its internal methods but you could still test that it WAS calling these methods.

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

+7  A: 

TypeMock Isolator can mock 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 don't depend exclusively on interfaces; they should be able to handle concrete classes just as well, although they'll only be able to override virtual or abstract methods.

Mark Rushakoff
your right when you say its not cheap $451.00 for a single licence
Chris G
Thanks for the answer but I need something free and that is not dependent on any kind of virtual\abstract methods
Chris G
i had fairly good sucess on moq on a big sized project.
Surya
+6  A: 

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

The best option is to refactor your existing code for testability (which may take time). I'd recommend reading Working Effectively with Legacy Code by Michael Feathers.

TrueWill
Thanks for pointing me towards the book I always enjoy a recommendation
Chris G
+6  A: 

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

Here and here (Channel 9) you can find an example on how to stub DateTime.Now. Using Moles, you can mock anything you want.

Ronald Wildenberg
@Ronald Was a little late sorry
Chris G
A: 

A lot of .NET mocking frameworks use Castle Dynamic Proxy to create mocks at runtime. Hence the limitation of only allowing interface/virtual methods to be mocked comes from Castle and I think is rooted in CLR. Both MOQ and RhinoMocks are able to mock virtual methods, which is as good as it gets.

Both classes and interfaces can be proxied, however only virtual members can be intercepted.

My advice would be to start creating abstract bases for those classes that need to be mocked and have the concrete class extend it. Then the abstract base can be passed around and mocked. It really is a refactoring exercise that is not overly complex.

Igor Zevaka