简体   繁体   中英

Non Interface dependent Mocking Frameworks for C#

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.

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM