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


 


 

About Jeremy Miller

Jeremy is the Chief Software Architect at Dovetail Software, the coolest ISV in Austin. Jeremy began his IT career writing "Shadow IT" applications to automate his engineering documentation, then wandered into software development because it looked like more fun. Jeremy is the author of the open source StructureMap tool for Dependency Injection with .Net, StoryTeller for supercharged acceptance testing in .Net, and one of the principal developers behind FubuMVC. Jeremy's thoughts on all things software can be found at The Shade Tree Developer at http://codebetter.com/jeremymiller.
This entry was posted in Test Driven Development. Bookmark the permalink. Follow any comments here with the RSS feed for this post.
  • http://www.jeffreypalermo.com Jeffrey Palermo

    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.

  • http://www.ayende.com/Blog/ Ayende Rahien

    The constructor will _always_ be exercised, in both Rhino Mocks and NMock, this is enforced by the run time.