01 October 2007

How to talk Mock

Brian Marick has posted an interesting proposal for changing the order of the pieces within a unit test. For example, he suggests moving from

def test_checker_normally_checks_network_once 
  checker = testable_checker # creates checker using mocks.
  @network.should_receive(:ok?).once.with(”url”).and_return(true) 
  checker.check(”url”) 
end

to

def test_checker_normally_checks_network_once 
  checker = testable_checker 
  during { 
    checker.check(”url”) 
  }.behold! { 
    @network.should_receive(:ok?).once. 
             with(”url”).and_return(true) 
  } 
end

which shows what you can do if you have a language with useful constructs.

Personally, I've tended to think of stubs and expectations in terms of pre-conditions and post-conditions, so I find the pre-test setup less disturbing—and I've been doing it so long I don't see it any more. I imagine it's rather like getting used to (+ 1 2), which Brian ought to recognise. If I were to have a go, I think I might try to write some like this:

during {
  checker.check("url")
}.expect_to_see {
  @network.ok?("url") { returning true }
  @timesink.sleep_for(32.minutes) { 6.times }
  but_not @listener.inform
}

It's nice to see someone experimenting with the ideas.

No comments: