Jeremy D. Miller -- The Shade Tree Developer

Sponsors

The Lounge

News

Advertisement

Images in this post missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at imagehelp@codebetter.com
Be Careful Mocking Concrete or Abstract Classes

I had a question today about whether you could just mark methods as virtual on a concrete class so they could be mocked, or if you should just extract an interface and mock that.  In a statically typed language like C# the safest answer in my book is to extract an interface.  Here's a bit of a reprint from an earlier post on this subject with some additional highlighting:

I would urge a certain level of caution in mocking an abstract class or a concrete class.  For best results my advice is to only mock interfaces to avoid unwanted side effects.  It is certainly possible to mock an abstract class, doing that leads to some side effects that effectively negate all of the advantages of a mock object.  Dynamic mock object tools like NMock or Rhino Mocks can only override virtual methods.  This might not be so much a problem in other languages, but with the .Net languages all methods are non-virtual by default.  This means that some of the behavior that you were trying to remove from the test with a mock is still there.  The dynamic mock libraries work by using Reflection.Emit to create a dynamic proxy on the fly for the requested interface or abstract class.  In the case of an abstract class the dynamic mock can only intercept virtual members and even worse, the constructor function of the superclass will probably be exercised. 

http://codebetter.com/blogs/jeremy.miller/archive/2006/01/10/136407.aspx

 

 


Posted 02-20-2006 12:42 PM by Jeremy D. Miller

[Advertisement]

Comments

Ayende Rahien wrote re: Be Careful Mocking Concrete or Abstract Classes
on 02-20-2006 2:23 PM
The constructor will _always_ be exercised, in both Rhino Mocks and NMock, this is enforced by the run time.
Jason Haley wrote Interesting Finds
on 02-21-2006 8:36 AM
Jeffrey Palermo wrote re: Be Careful Mocking Concrete or Abstract Classes
on 02-21-2006 2:06 PM
I would add that the only safe scenario for mocking classes are for classes that you control. In this way, you have control over constructor logic as well as what methods to mark as virtual. I've found that the need to mock a class is much less frequent than the need to mock an interface.
The Tomes Of Experience » Being driven down a path wrote The Tomes Of Experience » Being driven down a path
on 05-14-2008 8:26 PM

Pingback from  The Tomes Of Experience    » Being driven down a path

Mocking concrete classes using Rhino.Mocks « AB Kolan’s Blog wrote Mocking concrete classes using Rhino.Mocks « AB Kolan’s Blog
on 01-23-2009 11:40 PM

Pingback from  Mocking concrete classes using Rhino.Mocks « AB Kolan’s Blog

Add a Comment

(required)  
(optional)
(required)  
Remember Me?