Tuesday, November 17, 2009

How much code did I just delete?

Today I had the great pleasure of deleting a huge chunk of old code from my application. Using git it's surprisingly easy to figure out exactly how much code:
 
git checkout -b deletion_task

# ... delete lots of code...
# ... time passes...

git add -i
git commit
git co master
FILES_DELETED=`git diff --summary master deletion_task | grep "^ delete" | wc -l`
LINES_DELETED=`git diff --summary master deletion_task | grep "^ delete" | awk '{ print $4 }' | xargs cat | wc -l`
echo -e "$FILES_DELETED files deleted.\n$LINES_DELETED lines deleted."

Monday, November 16, 2009

Introducing Gimme: a lightweight ruby Registry

I recently created Gimme, a small ruby gem which allows you to configure and access a simple Registry using a nice little DSL.

Gimme in a paragraph

The general idea of Gimme is to allow a single point for configuring the well known services which your application uses (think DB connection, twitter API gateway, email server, etc). Once configured Gimme then exposes a single point to access those services, without needing to resort to singletons or global variables.

Show me teh codez

Here's a simple example showing how you would configure your registry:
Gimme.configure |g|
  g.for_the(ExternalService) do |env,name|
    ExternalService.new(env[:setting1],env[:setting2])
  end
end
and here's how you'd use it from within your app:
Gimme.the(ExternalService).some_method
Here's a more complete example, showing both configuration and usage:
# your Emailer class

class Emailer
  def initialize( smtp_hostname, port )
    @smtp_hostname, @port = smtp_hostname, port
    puts "creating an emailer: #{inspect}"
  end

  def send_email( subject )
    puts "Sending email '#{subject}' via #{inspect}"
    # ...
  end

  def inspect
    "#{@smtp_hostname}:#{@port}"
  end
end


# your Gimme configuration

Gimme.configure do |g|
  g.for_the( Emailer ) do |env|
    email_settings = env[:email_settings]
    Emailer.new(email_settings[:hostname],email_settings[:port])
  end
end

Gimme.environment = {:email_settings => {:hostname => 'smtp.mymailserver.com', :port => '2525'} }



# in your app


Gimme.the(Emailer).send_email( "Gimme is the awesomez" )
Gimme.the(Emailer).send_email( "Emailing is fun" )
Gimme.the(Emailer).send_email( "notice that only one Emailer was created above" )
Gimme.the(Emailer).send_email( "even though we sent 4 emails" )

Pseudo-singletons

If you use the Gimme#for_the(Service) form when configuring Gimme then gimme will only create one instance of that object. If you use the Gimme#for_a(Service) form then the creation block will be called each time you ask for an instance of that object. That way things which hold on to expensive resources (database connections, TCP sockets) can be shared within your app, which services which need to maintain unique state for each client can be private to each client.

Environments

In any non-trivial application you need to configure your services. You can supply Gimme with an environment hash which it will then pass to your creation blocks whenever you ask for an object. This allows you to store settings like smtp hostnames, database passwords, twitter API keys, etc in a single environment hash, and use that hash in one place to configure all your external services at the point they are created.

Dependency Injection/IoC

There is nothing to stop you from calling Gimme.a() or Gimme.the() from within a creation block. This allows you to use Gimme as a lightweight IoC container.

Check it out!

Check out the github page for more info, including lots of example usages, and a more detailed README.

Sunday, June 28, 2009

Adding hamcrest-as matchers to mock4as

Just a quick post to mention that I recently did an experiment with extending mock4as to use Drew Bourne's awesome hamcrest-as3.

The idea for this work is to specify mocked method arguments in a more flexible way. It was actually surprisingly trivial to implement. I'll be writing a more detailed post in the future explaining what these changes mean to a user of mock4as.

I also took the opportunity to experiment with using git and github, so the changes are available to all and sundry as a github repository. I will be talking to the mock4as guys about getting my changes merged into the official mock4as codebase

Sunday, June 14, 2009

Presentation Model Pattern

Presentation Model

We want to achieve a Skinny View without the View needing to expose UI details to the Controller.

Also known as

View State, Logical View

Problem

We want to have as much presentation logic under test as we can by having a Skinny View. At the same time we don't want our Controller to be burdened with the minutiae of maintaining UI elements.

Context

We are creating a presentation layer in Flex using some variant of MVC/MVP and want to implement controller logic which modifies the view.

Forces

  • Exposing individual UI elements to our controller makes tests fragile and tedious to write.
  • Burdening our controller with both abstract presentation logic (what to do when a user clicks a button) and concrete UI display logic (directly modifying the state of UI elements) violates SRP.
  • We want to take advantage of the powerful data binding functionality that Flex offers.
  • We do not want our Domain/Business logic to be polluted with UI layer details.

Solution

We create a Presentation Model that is a logical representation of the view. The controller maintains the view by manipulating the Presentation Model. We bind our view directly to the Presentation Model, so any changes to the Presentation Model are immediately reflected in the view.

To keep as much logic as possible out of the View and under test we advise not allowing the View to update the model directly. All updating must be done by the Controller. Often that will be initiated via a handler on the Controller called by the view in response to some user action.

Example

In this very simple example we will assume we're working on a Contact Manager application. Specifically we're working on a UI which contains a list of contacts and allows a user to add contacts to the list.

Presentation Model

We'll create a Presentation Model for that screen like this:

package com.example.contacts.ui
{
 import mx.collections.ArrayCollection;
 
 
 [Bindable]
 public class Model
 {
  public function Model()
  {
   names = new ArrayCollection();
  }
  
  public var names:ArrayCollection;
 }
}

View

Next we'll create a view which binds to that Presentation Model:

<?xml version="1.0" encoding="utf-8"?>

<mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" 
 width="600" height="600" 
 implements="com.example.contacts.ui.IView" 
 creationComplete="onCreationComplete()">
 <mx:HBox>

  <mx:VBox>
   <mx:Form height="100%" width="100%">
   <mx:FormItem label="First Name:">
    <mx:TextInput id="tiFirstName"/>

   </mx:FormItem>
   <mx:FormItem label="Last Name:">
    <mx:TextInput id="tiLastName"/>
   </mx:FormItem>
   <mx:Button label="Add Contact" click="onAddContactClick()"/>

  </mx:Form>
  </mx:VBox>
  <mx:VBox>
   <mx:List id="cbNames" dataProvider="{_model.names}" />

  </mx:VBox>
 </mx:HBox>

<mx:Script>
 <![CDATA[
  import com.example.contacts.*;
  
  private var _controller:Controller = null;
  
  [Bindable]
  private var _model:Model = null;
  public function set model( value :Model ):void {
   _model = value;
  } 

  private function onAddContactClick():void {
   _controller.onAddName( tiFirstName.text, tiLastName.text );
  }
 
  public function clearNameInputFields():void {
   tiFirstName.text = '';
   tiLastName.text = '';
  }
 ]]>
</mx:Script>
</mx:Canvas>

Controller

Finally we'll implement our Controller:

package com.example.contacts.ui
{ 
 public class Controller
 {
  private var _model: Model;
  private var _view : IView;

  public function Controller() {
   _model = new Model();
   _view = null;
  }
  
  internal function bindView(view: IView): void {
   _view = view;
   _view.model = _model;
  }
  
  internal function onAddName( firstName:String, lastName:String ):void {
   _model.names.addItem( lastName + ", " + firstName );   
  }
 }
}

Communication Diagram

The communication diagram above shows how the three classes collaborate to handle a user interaction event. The user takes an action, which results in an event handler in the View being called. The View's event handler delegates immediately to a handler method in the Controller. The Controller's handler method performs whatever logic is necessary, including updating the Presentation Model. That update indirectly triggers Flex data binding to update the View's UI elements. Note that communication tends to travel in one direction here - From View out to Controller, from Controller to Presentation Model, and from Presentation Model back to View. It is rare for a Controller to communicate directly with its View, and it is expressly forbidden for a View to directly manipulate the Presentation Model.

Note that the View is very skinny - it mostly just binds to the model and delegates handlers straight through to the Controller. Also note that the controller doesn't interact directly with the View when manipulating the UI. It just manipulates the Presentation Model, which results in the UI updating thanks to the View's data binding.

You can also see that we didn't follow the Pattern dogmatically in this example. We could have pulled the View's clearNameInputFields() method into the Controller by representing the contents of those 2 input fields in the Presentation Model and then binding those to the view. That would then allow us to clear the input fields by clearing the corresponding Presentation Model properties. However, in this case I decided that it was a nicer separation of concerns to hide the details of those elements from the Controller and the Presentation Model. Instead the View exposes a simple method with an Intention Revealing Name. This removes the need for the Presentation Model to be cluttered with these elements just to serve the one operation of clearing the fields.

This is a very basic example, but hopefully it conveys the concept. For a more sophisticated UI the View would have additional UI elements which would be bound to additional properties added into the Presentation Model.

Resulting Context

  • It is extremely easy to test how our Controller is modifying our View.
  • Our View no longer has to expose its UI elements.
  • Our Controller no longer has to deal with the View's UI elements.
  • Data binding allows our View to contain very little logic related to updating UI elements.

Rationale

It is really powerful to take advantage of data binding in Flex in order to simplify your view logic. At the same time it doesn't make sense to bind directly to our domain model classes. These classes are focused on representing the relationships and rules of our business domain, and should not be concerned with the UI layer at all. We need to map domain concepts like 'Collection Of Users' to UI concepts like 'list of strings for a dropdown'. Presentation Model allows us to do that. Presentation Model also allows us to very easily test the way our Controller updates the UI. Our tests simply have to exercise the Controller logic that is under test and then check the state of the Presentation Model.

Related Patterns

Presentation Model is really just a twist on Fowler's Two Step View, focusing on MVC/MVP and with a consideration of Flex data binding.

Authors

Pete Hodgson, Hosung Hwang

Sunday, April 19, 2009

REST: 'There aren't enough verbs'

I think one of the more frequent issues that people have when starting to work with a RESTful architecture is that "there aren't enough verbs".

Why having few verbs is good

When we look at the big picture we see that this paucity of verbs is in fact one of the strengths of REST. A small, standard set of verbs allows all parties to agree (in the most part) on what the semantics of those verbs are. This in turn allows the creation of a lot of loosely coupled infrastructure which any REST system can take advantage of. An obvious example is the sophisticated caching system within the world wide web. All parties can agree on what a GET means, specifically that it's an idempotent operation. That allows intermediaries to know when a response is cachable. If each application was creating its own set of verbs we'd no longer be able to leverage all this 'free' infrastructure which has built up. If a cache somewhere between your user's browser and your data center doesn't understand what the semantics of some custom verb are then it can't safely cache your responses. Same goes for your user's browser. This is one of the reasons why RESTful folks don't like web services with RPC-style architectures. By tunnelling everything through POST and a single URI these services lose the ability to confer semantics to intermediaries. These kinds of services are on the web, but not of the web.

What to do when you 'need' more verbs

So, we are agreed that a small, standard set of verbs is a good thing. What then is an API designer to do when modeling a complex operation which doesn't map nicely onto that small set? In my experience there are generally two solutions. We can use an overloaded POST, or we can add some additional 'activity resources' to the resource space of the API. I tend to prefer the latter, but I think it's important to not be dogmatic about this. There are certainly situations where an overloaded POST is the way to go.

Let's discuss what I mean by 'activity resources'. Generally when people start designing the resource space for their RESTful API they might write a description of what functionality the API seeks to expose, and then go through the text underlining nouns. If this is reminding you of an analysis technique for a certain other paradigm then stick with me, I'll be coming back to that in the next section. This set of nouns would generally be a good starting point for identifying resources. I'll call these types of resources Entity Resources. Let's say we're working on a hotel reservation system. After this initial stage of analysis we might come up with a set of entity resources such as Guest, Room, Hotel, Bill, etc. We'd probably also have Reservation in there too, but I wouldn't classify that one as an entity. So far so good. Now, let's say we're working on the checkout part of the system, in particular on credit card processing. We need a way to represent the act of a Guest paying their Bill with a credit card, having that credit card transaction approved or declined, etc. A lot of developers (particularly those coming from an RPC mindset) will want to do something like add a PAY verb to the Bill resource. This makes sense. Paying is an action that is applied to the Bill. It makes sense, but as we've discussed above REST frowns upon extending our small set of verbs. So instead we can create an Activity Resource called Payment. This resource can contain a reference (in the form of a uri) to the Bill it is a Payment for, along with details like credit card number, etc. In addition we can add a Payments resource which belongs to each Bill. When a customer wants to pay a bill they can send a POST to the Payments resource, supplying a representation of the payment they want to make. That POST will create a Payment resource representing the transaction, and supply the user with a uri for that resource in the form of a redirect. The customer can GET on that resource to check on the state of the payment transaction (Processing,Successful,Denied), etc. Maybe if the payment was denied they could PUT to the resource with a corrected credit card number. The key pattern here was to take an action (paying a bill), and to model that as a transitory Activity resource. Adding that extra level allows us to model the behavior in a RESTful way. I've frequently seen transactions modeled RESTfully in this way.

Sidebar: Parallels in grokking REST and grokking OO

When I was going through the slow, laborious process of getting these ideas into my thick skull I experienced a vague feeling of déjà vu. I eventually realized that this was just like when I first started to really grok object-oriented design. Often when students are being taught to design object oriented systems a suggested technique is to write a description of the business domain and then underline the nouns in the description. These nouns will be the classes in your system. However, after gaining experience with OO I think most developers realize that these classes are not where the meat of a design lies. The meat lies in the interaction between these entities, how they are composed and how they interact. Using polymorphism and composition to create clean, loosely-coupled systems becomes much more interesting than designing the Is-A inheritance heirarchies that often appear in introductions to OO. And here lies the parallel with learning RESTful design, and my sense of déjà vu. When learning REST the core concepts of Resources, Actions, Uris, etc. are necessarily explained first, and most pedagogical examples focus on simple systems consisting of what I referred to above as Entity Resources. However when you start to do real work with a RESTful architecture you start realizing that large parts of the system are about modeling the relations and interactions between these Entity Resources. I expect that as we gain more experience with the REST style then the common problems and shared solutions will start to emerge, in the same way as we saw OO design mature in the 80s and 90s.

Thursday, April 2, 2009

mock.willExecute(...) in mock4as

As I mentioned in a previous post I've recently been adding some features to mock4as, a mocking library for ActionScript. In this post I'm going to talk about the new mock.willExecute(...) feature which I recently implemented.

Perhaps the easiest way to describe willExecute is as a dynamic version of willReturn, so before we dive into willExecute I should briefly explain willReturn. willReturn allows a user to specify what value a mocked out method should return when called. An example should shed some light:
var mock:MockInterface = new MockInterface();
mock.expects('lookupBookTitleByISBN').withAnyArgs().willReturn('War and Peace');
assertEquals( 'War and Peace', mock.lookupBookTitleByISBN() );
You can see that when we call the method mock.lookupBookTitleByISBN() it returns 'War and Peace', because that's what we specified in our expectation. This is a fundamental feature that I would expect any mocking system to supply. It's the primary tool for controlling the indirect inputs into the system that your testing. That said, newcomers to mocking do sometimes get confused with this feature and think that willReturn is specifying what you expect the method to return. That's not what we're doing here, we're instructing the mock what to return. We're providing indirect input, not testing indirect output (the other main purpose of mocking). I suspect that adding a new method to mock4as which is similar mock.expects(...) but intended for use in cases where you just mocking the method to control indirect input would be helpful. Something like mock.ifCalled('foo').willReturn(someResult) might clear up some of the confusion between specifying an expectation that a method is called and injecting a return value for a method.

Anyway, back to the subject at hand. The willExecute feature takes the concept of willReturn and makes it dynamic. Rather than specifying a hard-coded value to be returned whenever the method is called you instead supply an arbitrary function which will be executed whenever the specified method on the mock is called. For example:
var mock:MockInterface = new MockInterface();
mock.expects('lookupBookTitleByISBN').willExecute(
  function( isbn:String ):String{
    return "Title for isbn " + isbn;
  } );

assertEquals( 'Title for isbn ABC', mock.lookupBookTitleByISBN('ABC') );
assertEquals( 'Title for isbn XYZ', mock.lookupBookTitleByISBN('XYZ') );

Every time lookupBookTitleByISBN(...) is called the mocking system looks up and executes the attached function, passing in the arguments supplied to lookupBookTitleByISBN(...). In addition it returns whatever value was returned by the attached function. Note from our example that this allows output to vary with the input, because we have supplied a function rather than a static value.

The real fun starts when we realize that functions in actionscript can act as closures. This leads to a lot of interesting ways to use willExecute. To give one (rather contrived) example, we can use willExecute to specify some quite sophisticated ordering constraints:

public function test_accountsAreSubmittedInAscendingNumericalOrder():void {
  var mock:MockInterface = new MockInterface();

  var lastAccountId:int = -1;
  mock.expects('submitAccount').withAnyArgs().willExecute(
    function(account:account):void {
      assertTrue( account.id() >= lastAccountId );
      lastAccountId = account.id();
    }
  );

  exerciseSystemUnderTestUsing( mock );
}

Note here that we have used variables outside of the closure's local scope to maintain state across calls to the mocked method. Also note that we can call methods like assertTrue(...) from inside the attached function.

Some other potential uses of this feature include:

Verifying arguments passed to a method where the argument is complex: Let's say a method takes a Parameter Object which is an instance of a class with 10 properties, but we're only interested in three:

public function testXYZCoordinatesAreAllSetToZero():void
{
  var mock:MockSomeInterface = new MockSomeInterface();

  mock.expects('methodWithScaryParams').withAnyArgs().willExecute(
    function(bigObject:ComplexParameterObject):void{
      assertEquals( 0, bigObject.coordX );
      assertEquals( 0, bigObject.coordY );
      assertEquals( 0, bigObject.coordZ );
    }
  );

  exerciseSystemUnderTestUsing(mock);
}

Verifying arguments passed to a method with a lot of parameters but where we're only interested in some of the arguments:
public function testNameAndAddressAreNotEmpty():void
{
  var mock:MockSomeInterface = new MockSomeInterface();

  mock.expects('methodWithManyParams').withAnyArgs().willExecute(
    function(boring:String,uninteresting:XML,name:String,address:String,dontCare:Function):void{
      assertNotEquals( "", name );
      assertNotEquals( "", address );
    }
  );

  exerciseSystemUnderTestUsing(mock);
}

Verifying some internal characteristics of an argument:
public function testNameAndAddressAreNotEmpty():void
{
  var mock:MockSomeInterface = new MockSomeInterface();

  mock.expects('someMethod').withAnyArgs().willExecute(
     function(lotsOfXml:XML):void{
      assertEquals( "Dave", lotsOfXml.body.person.firstName );
      assertEquals( "Thomas", lotsOfXml.body.person.lastName );
    }
  );

  exerciseSystemUnderTestUsing(mock);
}

It's interesting to note that willExecute can be used to accomplish two goals. You can use it to control the Indirect Input into the system you're testing (which is what willReturn is also used for, as I touched on above). In addition you can also use it to test the Indirect Outputs of your system. This is what's happening above when assertEquals(...), assertTrue(...) and the like are called from within the attached functions. My personal experience is that something like willExecute tends to be used more often as an ad hoc way of testing Indirect Output than as a way of supplying Indirect Input (which can most time be handled adequately using willReturn). Most of the time I use it to express non-trivial expectations on the input to a method. In a lot of frameworks the need to do this is reduced by the presence of custom argument matchers. These allow you to capture complex expectations on a method's input parameters by implementing classes which you then provide to your mock during the expection setting phase. For examples from other mocking frameworks you could look at jMock and Mockito.

Finally, you may remember I started off describing willExecute above is as a dynamic version of willReturn. In fact, willReturn could be trivially implemented using willExecute:

public function willReturn(object:Object):void{
  willExecute( function():Object{ return object; } );
}

The same is true of the willThrow() feature (which allows a user to ask a mock to throw a specific exception when a method is called).

public function willThrow(error:Error):void{
  willExecute( function():void{ throw error; } );
}

Wednesday, April 1, 2009

fun with Symbol#to_proc

As I start to get fluent in ruby I often find myself using a more functional programming style, particularly when dealing with collections. That generally leads to lots of little block-centric operations. I recently discovered a really elegant trick to make that code a little nicer.

Let's say there's a Person class:
class Person
    attr_accessor :first_name, :last_name, :age
end
and I have a collection of people which I'd like to sort by age. An obvious approach would be:
people.sort_by{ |person| person.age }
That works, but it is a little wordy. This is ruby, after all! Wouldn't it be nice if we could write this instead:
people.sort_by &:age
Isn't that neat? The magic that makes this work is this little monkey patch to the Symbol class.
class Symbol
  def to_proc
    Proc.new { |*args| args.shift.__send__(self, *args) }
  end
end
Note that this is already done for you in Rails and in Facets - in fact that's where I lifted this code from.

So how does this work? When we called sort_by we passed in the :age symbol, but we used the & to indicate that it should be treated as a block. When you supply a method with a block which isn't a Proc instance ruby helpfully attempts to coerce it into a Proc by calling to_proc. Because of the Symbol monkey patch to_proc now returns a block which will invoke a method with the same name as the symbol itself on whatever object it is passed in. Phew. Re-read that last sentence 5 times. The end result is that the following two blocks are identical:
block_a = :some_method.to_proc
block_b = proc { |x| x.some_method }
It follows that the following two operations are identical:
people.sort_by{ |person| person.age }
people.sort_by &:age
Voila! I should point out here that I'm not exactly the first person to discuss this great trick. See for messirs Thomas and Williams.

In fact, it's such a common idiom that it will apparently be baked right into ruby 1.9.

Monday, March 23, 2009

Liberal Mocks

I've been using mock4as recently as part of a drive to get better test coverage in a flex project. As I used it I noticed a few features which I've seen in other mocking libraries that were missing. I did what any engineer with an itch to scratch might do in such a situation - I started to implementing the features in mock4as that I wanted to use.

One of the things I added was support for a pattern/feature which I'm going to refer to here as 'liberal mocks'. I am not really sure what the right name for this pattern is. I've seen it called 'null object' before, and also 'stubs'. In my opinion both those terms are too overloaded to be used in this context, although the Null Object pattern is very similar to what I'll be describing.

I definitely wouldn't use the word 'stub' in connection to this pattern, although I've seen that done in other mocking libraries. For a start there is already way too much confusion in automated testing between Stubs and Mocks. For the record, my definition of a Stub is pretty close to what's described in the XUnit Test Patterns book (which I highly recommend). It's a Test Double which is used to control indirect input into a system under test, and possibly to record indirect output for later verification. That second part is where my definition differs from Meszaros's - I merge Test Stub and Test Spy together. Anyway, I'd love to hear from anyone who has a better (or more 'correct') name for the pattern I'm describing.

On to the main attraction. A Liberal Mock is a mock which will not fail when it receives an unexpected method. Instead it will silently ignore the method call. Contrast this to a regular, or 'strict' mock. In most mocking libraries a standard mock which receives a method call that was not specified while the mock's expectations were being set will be considered an error, and the mock will not pass verification.

A couple of unit tests from the mock4as library's test suite should help to illustrate this:

public function
testFailsIfUnexpectedMethodCalled():void
{
  var mock:MockSomeInterface = new MockSomeInterface();
  mock.doSomething();
  assertFalse(mock.success());
}

public function
testSuccess_whenUnExpectedMethodCalledOnLiberalMock():void
{
  var mock:MockSomeInterface = new MockSomeInterface();
  mock.isLiberal();
  mock.doSomething();
  assertTrue(mock.errorMessage(), mock.success());
}

That covers the what, now on to the why. The main scenario where I find myself reaching for liberal mocks is when I have a method which uses several features of a dependency, but I'm writing a test which is only interested in certain aspects of that usage. For example, let's say I have a controller object which is responsible for maintaining a view object. The controller has an initialize() method which sets the view's UI elements to some initial state, and I'd like to get that method under test. Now if the view has a lot of UI elements I wouldn't want to test all of the setup in one test. Instead I might want tests like initialize_shouldSetupCampaignDropDownCorrectly(), initialize_shouldSetupDaypartingViewWithModelContents(), etc. If I was mocking the view with a strict mock then every test would need to explicitly set expectations for all the calls which the controller will be making to the view, even if each individual test is only interested in a small subset of those calls. With liberal mocks that requirement is removed. I can essentially say 'this dependency is going to be used in a bunch of ways here, but I'm only concerned with these specific method calls'. The underlying motivation for this is to avoid Fragile Tests. If you're not using liberal mocks and one aspect of your expected behavior changes then suddenly all your tests will fail, not just the test that specifies the behavior that's just changed. Fragile tests seem to be a common risk for new automated testing practitioners, and they can be really demoralizing.

Now, just because you can doesn't always mean you should. I've found that liberal mocks can be a bit of a crutch for a less-than-optimal design. If you find yourself needing to use a lot of liberal mocking then you should consider that to be a design smell. Maybe the method you're testing is doing too much work. If you can break your big method up into smaller methods that are testable then you're in a happier place, in terms of testing and more importantly in terms of design. Alternatively, the issue may be that the dependency which you're mocking out has some huge sprawling interface that should be split into several pieces. After doing that you may find that you only need to set expectations on one of those pieces, and the other parts can be replaced with a true Null Object.