CodeBetter.Com
CodeBetter.Com
RSS 2.0 via Feedburner
           Do you Twitter? Follow us @CodeBetter

Jeremy D. Miller -- The Shade Tree Developer

Under the hood and working with .Net, TDD, Software Design, and Agile Stuff

Mock Objects and Stubs: The Bottle Brush of TDD

I’m in a dry spell for blogging, so here’s a rehash of a presentation I gave internally at work earlier this year.  The general topic of mock objects comes up pretty often at our Agile Austin lunches, so I figure mocks are worth some blogging space anyway.  This is the first of 4 posts on the subject of mock objects and stubs.

 

  1. Introduction to Mocks and Stubs (this post)
  2. When and Why to use Mocks and Stubs
  3. Best Practices for Mocks
  4. Constraints and other Mocking Tricks
  5. Attaching Mocks and Stubs with StructureMap (by request)

 

 

Test Driven Development always seems pretty simple in the introductory tutorials.  Assert that the result of 2 + 2 equals 4, check.  Then Monday morning you go back to the real world of enterprise application development and you’re suddenly faced with relational databases, middleware, web services, and all manner of security infrastructure.  For a variety of reasons, interacting with external resources can make your automated tests a lot harder to write, debug, and understand.  Even worse, those external resources may make your tests indeterminate (think shared database).  You’ll frequently hear teams say they didn’t write unit tests for a particular area of the code because it was just too hard to test.  I think one of the biggest challenges of using TDD is learning strategies for isolating the code that’s hard to test and writing code that is easy to test.  One of the primary strategies to extend unit test coverage into those hard to reach places is to use mock objects, stubs, or other fake objects in place of the external resources so that your tests don’t involve the external resources at all.

 

One of the central pillars of Object Oriented programming is polymorphism -- the ability to interchangeably utilize multiple implementations of a well-defined interface.  We’ve all seen way too many silly examples of Beagle inheriting from Dog which implements IAnimal.  Here’s a more realistic and powerful utilization of polymorphism.  You’re tasked with building a new reporting website to display data from the old legacy COBOL inventory system (you know, the one where the column names are COL0023 and the tables are D05A10).  The legacy system team is struggling to get the data access code done because the database structure doesn’t make the slightest bit of sense.  You’d like to get started with constructing the website, so you define the interface of the data access class and create a stub class that just reads data from an xml file instead of the legacy code.  You can get on with your work and focus on the user interface functionality.

 

      public interface IDataSetSource

      {

            DataSet FetchReport(DateTime from, DateTime to);

      }

 

      public class StubbedDataSetSource : IDataSetSource

      {

            public DataSet FetchReport(DateTime from, DateTime to)

            {

                  DataSet dataSet = new DataSet();

                  dataSet.ReadXml("ReportData.xml");

 

                  return dataSet;

            }

      }

 

      public class DataSetSource : IDataSetSource

      {

            public DataSet FetchReport(DateTime from, DateTime to)

            {

                  // run a query or a stored procedure against the database and return

                  // a DataSet of the results

            }

      }

 

      // ReportController depends on the IDataSetSource interface, not a particular

      // implementation or even backend data store

      public class ReportController

      {

            private IDataSetSource _source;

 

            public ReportController(IDataSetSource source)

            {

                  _source = source;

            }

      }

 

What’s the Difference between a Mock and a Stub?

 

Stubs have been around as long as object oriented programming and they’re well understood.  Mock objects on the other hand are a relatively new concept that seems to generate a great deal of confusion.  A common misconception about mocks and stubs is that the difference is that stubs are static classes and mocks are dynamically generated classes created by some kind of tool like NMock.  That’s a false dichotomy.  The real difference between a mock and a stub is in the style of unit testing, i.e. state-based testing versus interaction testing.  A stub is a class that is hard-coded to return data from its methods and properties.  You use stubs inside unit tests when you’re testing that a class or method derives the expected output for a known input. 

 

A mock object is a tool for interaction based testing.  You use a mock object to record and verify the interaction between two classes.  Roy Osherove made my all time favorite explanation of mock objects by comparing a mock object to a spy that listens to the interaction between two classes. 

 

The typical usage of a mock object is roughly the 5 step process below.

 

  1. Create the mock object
  2. Set the expectations on the mock object
  3. Create the class that’s being tested
  4. Execute the method that’s being tested
  5. Tell each mock object involved in the test to verify that the expected calls were made

 

Here’s an example from a model view presenter pattern using NMock to create dynamic mock objects.

 

            [Test]

            public void CloseViewWhenViewIsNotDirty()

            {

                  // 1.) Create the mock objects

                  IMock msgBoxMock = new DynamicMock(typeof(IMessageBoxCreator));

                  IMock viewMock = new DynamicMock(typeof(IView));

 

                  // 2.) Define the expected interaction

                  msgBoxMock.ExpectNoCall("AskYesNoQuestion", typeof(string), typeof(string));

                  viewMock.ExpectAndReturn("IsDirty", false);

                  viewMock.Expect("Close");

 

                  // 3.) Create the presenter class with the mock objects

                  Presenter presenter = new Presenter(

                        (IView) viewMock.MockInstance,

                        (IMessageBoxCreator) msgBoxMock.MockInstance);

 

                  // 4.) Perform the unit of work

                  presenter.Close();

 

                  // 5.) Verify the interaction

                  msgBoxMock.Verify();

                  viewMock.Verify();

            }

 

Dynamic versus Static

 

Both mocks and stubs can be implemented as either a dynamically emitted class or a static class that you roll on your own.  Here’s an example stubbing security done both statically and dynamically.

 

      public interface ISecurityDataStore

      {

            bool Authenticate(string userName, string password);

            string[] GetRoles(string userName);

      }

 

      // Static stub

      public class StubbedSecurityDataStore : ISecurityDataStore

      {

            public bool Authenticate(string userName, string password)

            {

                  return true;

            }

 

            public string[] GetRoles(string userName)

            {

                  return new string[]{"Admin", "Write", "Read"};

            }

      }

 

      [TestFixture]

      public class AuthenticationTester

      {

            public void AuthenticateSuccessfullyAndCreateTheCorrectPrincipal()

            {

                  // Create a dynamic mock object for ISecurityDataStore, but use it

                  // like a stub.  I don't call Verify() on the dataStoreStub object

                  // because I'm just testing the state of the GenericPrincipal object

                  // that is returned by authenticator

                  IMock dataStoreStub = new DynamicMock(typeof(ISecurityDataStore));

                  string[] theRoles = new string[]{"role1", "role2"};

 

                  // setup dataStoreStub.MockInstance to return theRoles anytime the "GetRoles" method

                  // is called

                  dataStoreStub.SetupResult("GetRoles", theRoles, null);

 

                  Authenticator authenticator = new Authenticator((ISecurityDataStore)dataStoreStub.MockInstance);

 

                  GenericPrincipal principal = authenticator.CreatePrincipal("Jeremy", "ComplexPassword");

                 

                  Assert.IsTrue(principal.IsInRole("role1"));

                  Assert.IsTrue(principal.IsInRole("role2"));

                  Assert.IsFalse(principal.IsInRole("role3"));

            }

      }

 

We’ve already looked at several examples of dynamic mocks, so here’s an example of what a static mock for ISecurityDataStore might look like.

 

      public class MockSecurityDataStore : ISecurityDataStore

      {

            private string _expectedUserName;

            private string _expectedPassword;

            private string[] _roles = new string[0];

            private bool _authenticationSuccess = false;

            private bool _authenticateWasCalled = false;

 

            public MockSecurityDataStore(string expectedUserName, string expectedPassword, bool authenticationSuccess)

            {

                  _expectedUserName = expectedUserName;

                  _expectedPassword = expectedPassword;

                  _authenticationSuccess = authenticationSuccess;

            }

 

            public string[] Roles

            {

                  get { return _roles; }

                  set { _roles = value; }

            }

 

            public bool Authenticate(string userName, string password)

            {

                  Assert.AreEqual(_expectedUserName, userName, "Unexpected user name");

                  Assert.AreEqual(_expectedPassword, password, "Incorrect password");

 

                  _authenticateWasCalled = true;

 

                  return _authenticationSuccess;

            }

 

            public string[] GetRoles(string userName)

            {

                  Assert.AreEqual(_expectedUserName, userName, "Unexpected user name");

                  return _roles;

            }

 

            // Call this method to verify the Authenticate() method was called at all

            public void VerifyExpectations()

            {

                  Assert.IsTrue(_authenticateWasCalled, "The Authenticate() method was never called");

            }

      }

 

I definitely have my preferences in the static versus dynamic mock debate, but at various times I’ve used all four permutations.  I like to use static mocks whenever I’m faced with a lot of name/value pairs or set based arguments.  I have a static mock class in my rough equivalent of the Enterprise Library’s data access framework that validates the correct parameter values for the invocation of any database command (I still think it’s a clever implementation, but we don’t use it very often).  Whatever your preference, I’d still try to be familiar with all of the options because each development project is different.  By all means, don’t blow off the dynamic mock tools just because they look scary at first view.

                                                                                            

The Case for Dynamic Mocks

 

My strong preference is to use dynamic mocks.  A lot of people avoid using dynamic mocks because they look weird at first and maybe aren’t the easiest thing in the world to understand.  I think that once you get past the initial learning curve dynamic mocking engines like NMock or RhinoMocks become easier to use.  I like dynamic mocks because you don’t have to clutter up your code with a bunch of extra classes for the static mocks.  Another great attribute of dynamic mocks is that you don’t have to implement the entire interface and you can essentially ignore the methods and members of the interface being mocked that aren’t involved in any particular unit test.  I really get irritated when I add a new method to an interface then spend a couple minutes chasing down all of the static mocks and stubs to add skeleton methods just to get the code to compile.  I also think that dynamic mocks are more flexible.  I’ve also found that dynamic mocks lead to writing less code because the mocking engine takes care of the assertion logic.

 

The Case for Static Mocks

 

The single biggest reason to use static mocks is simply a discomfort with dynamic mock engines.  I’ll easily grant you that the dynamic mock tools aren’t very well documented and they’re still relatively new.  Micah Martin of ObjectMentor has a good post on the pro-static mock case.  I don’t agree with Micah entirely, especially about his contention that mock tools aren’t flexible enough (but that’s a later post already on the way).  Where he’s definitely accurate is in warning us that dynamic mocks hamper refactoring.  Dynamic mocks aren’t “ReSharper-able.”  The compiler and ReSharper can’t find the method references in mock.ExpectAndReturn(“SomeMethod”, true) when you change the SomeMethod() to IsSomething().  The refactoring challenge in specific is why I’m taking a long, hard look at RhinoMocks to replace NMock in our development (that little Intellisense thing is pretty important too).

 

There’s a more general lesson in there though.  Using reflection of any kind can easily lead to brittle code that is harder to refactor.

 

 

 

 

Next up is a discussion on when and why to use mock objects…



Comments

Harris said:

Jeremy,

Great Post! And timely too...I just had a discussion this weekend about mocks, what they are, and why they're useful and I didn't drive home the point very well. Needless to say, the discussion group has received an e-mail referencing this post. Great Job!

Also, just thought I'd share with you that I use the Mock framework that is distributed with NUnit and find it easier to work with than NMock. i've just had better experience with it. The assembly should come with the downloadable bits - nunit.mocks.dll. The interfaces seem to be the same as NMock so, depending on your coding style, you "should" be able to just replace your references and be up and running.

Rhino.Mocks looks very interesting, but it's a shame the generic methods are not yet supported...

Take care and happy holidays,

H
# December 19, 2005 8:53 AM

John Woodard said:

I agree, great post. I'm just starting with TDD and will definitely check out NMock.

One thing that confuses me, however, and has been the subject of much debate among myself and my colleagues is this: I understand isolating the code from external factors for testing by wrapping them up in an abstractable class and using a mock in their place.

But don't you eventually have to test the code in the abstracted class? It just seems like, no matter how far you isolate things, eventually you have to test against the outside source.

Am I missing something here?
# December 20, 2005 7:05 AM

Jeremy D. Miller said:

John,

You're completely correct, you do have to write fully integrated tests at some point. I'd still say that for best results you unit test code with mocks before you even attempt to write the integrated test. Test small before you test big. Most of the XP teams I've seen or worked with will keep at least two libraries of NUnit tests. One assembly of unit tests and another of developer-written integration tests.


http://codebetter.com/blogs/jeremy.miller/archive/2005/07/27/129907.aspx
# December 20, 2005 8:42 AM

Douglas Rohm said:

Version 2.4 of Rhino Mocks added support for generic methods:

http://www.ayende.com/projects/rhino-mocks/documentation.aspx#Changes
# December 20, 2005 3:56 PM

Jeremy D. Miller -- The Shade Tree Developer said:

In the last post I introduced mock objects and talked about some of the various flavors of fake objects. ...
# December 20, 2005 5:23 PM

the blog of michael eaton said:

# December 21, 2005 10:01 AM

Ben Hale said:

As a paid Java developer who is really a closeted C# developer, it's rare that I get to say that something is better in Java than C#, but here it is. I currently use a package called EasyMock in Java that leverages dynamic proxying and our new found generics to create mocks that are refactorable. Basically you do something like expect(object.method()).andReturn(false). Now, you still need to make sure that you update all of the expected and return values, but at the very least you're getting good refactoring support.
# December 24, 2005 2:44 PM

Sam Gentile's Blog said:

# December 30, 2005 12:26 PM

Jeremy D. Miller -- The Shade Tree Developer said:

Mock objects are like any other tool.  Used one way they’re a huge time saver.  In other cases...
# January 10, 2006 6:01 PM

Jeremy D. Miller -- The Shade Tree Developer said:

A friend of mine was asking me a while back about ways to apply the Model View Presenter (the “Humble...
# February 1, 2006 11:18 PM

Jeremy D. Miller -- The Shade Tree Developer said:

Author: <a href="blogs/jeremy.miller/">Jeremy D. Miller</a><br />A friend of mine was asking me a while back about ways to apply the Model View Presenter (the “Humble Dialog Box”) pattern to ASP.Net development to promote easier unit testing of the user interface layer. Two weeks and a major case of writer’s block later, I finally finished the post. I wrote a blog post last spring describing the usage of MVP (“The Humble Dialog Box”) with WinForms clients, but web development in general and ASP.Net in specific comes with a different set of challenges.
# February 2, 2006 7:11 PM

Niklas Nihl said:

# March 30, 2006 12:56 PM

Niklas Nihl said:

# March 31, 2006 12:00 PM

Niklas Nihl said:

# March 31, 2006 12:04 PM

Jeremy D. Miller -- The Shade Tree Developer said:

This is the final post in the whole "Test Small Before Testing Big" saga.  I've tried to impress...
# July 3, 2006 1:51 PM

Jeremy D. Miller -- The Shade Tree Developer said:

Between being extremely short handed at work, tech' reviewing a new book, a
possible book proposal...
# August 7, 2006 4:51 PM

Jeremy D. Miller -- The Shade Tree Developer said:

Between being extremely short handed at work, tech' reviewing a new book, a possible book proposal

# September 1, 2006 2:33 PM

Jeremy D. Miller -- The Shade Tree Developer said:

Jay Kimble , CodeBetter's resident AJAX guru, issued a little challenge to us TDD bloggers about using

# March 7, 2007 2:06 PM

Dim Blog As New ThoughtStream(me) said:

Jeremy Miller has posted quite a response to a question asked by Jay Kimble on unit testing with the...

# March 7, 2007 5:05 PM

Console.Write(this.Opinion) said:

Como já falei mil vezes aqui minha coluna na última edição da Mundo.net veio falando sobre Mock object

# April 11, 2007 2:09 PM

Jeremy D. Miller -- The Shade Tree Developer said:

Author: Jeremy D. Miller A friend of mine was asking me a while back about ways to apply the Model View Presenter (the “Humble Dialog Box”) pattern to ASP.Net development to promote easier unit testing of the user interface layer. Two weeks and a major

# November 8, 2007 7:48 AM

Alec Lazarescu's Blog said:

I'll begin a series of posts that in no small part will serve as summaries/reminders to myself on various

# February 18, 2008 2:54 PM

Leave a Comment

(required)  
(optional)
(required)  

Enter the numbers above:
Add

About Jeremy D. Miller

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 previously worked as a systems architect building mission critical supply chain software for a Fortune 100 company and learned agile development practices as a .Net consultant at ThoughtWorks, one of the pioneers of agile development. Jeremy is the author of the open source StructureMap (http://structuremap.sourceforge.net) tool for Dependency Injection with .Net and the forthcoming StoryTeller (http://storyteller.tigris.org) tool for supercharged FIT testing in .Net. Jeremy's thoughts on just about everything software related can be found on his weblog "The Shade Tree Developer" at http://codebetter.com/blogs/jeremy.miller, part of the popular CodeBetter site. Jeremy is a Microsoft MVP for C#. Check out Devlicio.us!

This Blog

Syndication

News

All opinions expressed here constitute my (Jeremy D. Miller's) personal opinion, and do not necessarily represent the opinion of any other organization or person, including (but not limited to) my fellow employees, my employer, its clients or their agents.

About Me

"Best Of" Compendium

StructureMap (Dependency Injection for .Net)

StoryTeller (Supercharged Fit)

Build your own Cab

TestDriven

MVP