Lazy man's mock pattern

Sometimes you want to test not only each class in isolation but subset of one class in isolation. I suppose that in many cases this means that you actually have something wrong in your design and you should consider splitting responsibilities of given class or make the API more fine grained. However sometimes above options are not that good - for example in case of legacy code. We don't have time to refactor some old class but we still need to test if the code that we have added to it works correctly. In such situation I have started to use kind of a variation of self-shunt pattern.

Example:

class BlogManager {
   public void addComment(Comment newComment) {
      //our new code that checks if we need to notify about changes
      notifyChanges();  
   }
   protected void notifyChanges() {
     //very hairy legacy code that relies on database access, deployment environment etc
   }
}

We want to test that new method addComment() calls notifyChanges() correctly. Here is the test:

class  BlogManagerTest  {
 
  @Test
  public void notifyChangesIfAddingImportantComment() {
    MockBlogManager mgr = ...
    mgr.addComment(newComment);
    mgr.verify();
  }

  private static class MockBlogManager extends BlogManager {
      @Override
      protected void notifyChanges() {
          isCalled = true;
      }
      public void verify() {
         assertTrue(isCalled);
      }
  }

}

This pattern is a bit dangerous (as subclassing always is) because the methods you have overridden may have some other hidden preconditions that your new code fails to set up. However it gets you started.

Labels

mock mock Delete
testing testing Delete
Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.
  1. May 28, 2007

    Sven Filatov says:

    Cool. BTW, for some reason I see the page you referred to written with hierogly...

    Cool.

    BTW, for some reason I see the page you referred to written with hieroglyphs

    1. May 28, 2007

      Ürgo Ringo says:

      I can't say it was completely unintentional However for these few who are not ...

      I can't say it was completely unintentional

      However for these few who are not that interested in Eastern culture: http://c2.com/cgi/wiki?ShuntPattern