The way of the unusual architect - Dan North

An enlightening talk on 'how the human mind works and its corollaries on how programmers work' from the wise Dan North - founder-leader of the BDD camp..

...and so you go from something that was fit for purpose but a little bit ugly to something that never quite delivers. Who here has been involved in what I call a 2-year rewrite anti-pattern ? So we go to the business and we say

Ok.We will rewrite out entire system for some period of 2 years and then everything will be good.
'Wait hang on. What will we get after 2 years?'
Exactly what you've got now.
'Right... and during that 2 years..'
Oh we're locked down! We can't do anything else for you.
'Ok. So you're telling us that we should pay you for 2 years to go no further than we are now and you won't be able to do anything else'.
No.. that's pretty much it.
'Okay...'

and we call that enterprise architecture.

He had me there 3 mins into the talk. Recommended

Beacons - a VS 2010 Extension for TDD

Just uploaded an early version of a TDD visualization extension that I've been working on in my free time. Get an early version of Beacons from the google code project here


The extension only works with NUnit currently. You specify a file path to your NUnit test results file path (which is normally a TestResults.xml file in your .dll/.nunit folder) and you're all set to go.
It can't listen to Resharper test-runner yet. (yet.. if I can figure out how to tap in, should be not an issue.)


To see it in action, check out this video - switch to fullscreen HD


TDD StringCalculator Kata - Part1 from Gishu Pillai on Vimeo.
  • Shift+Alt+B, H - Change hats (adding behavior hat OR refactoring hat)
  • Shift+Alt+B, P - Play/Pause (when you need to take a break)
If you give it a fair try, I'd love to hear from you. Particularly I'm interested in finding patterns (so share end-of-session screenshots)
More ideas, comments, suggestions - feedback of any kind is welcome.. Post away at http://groups.google.com/group/beacons-tdd

ScenarioLibrary, LibraryTables with Slim Scenarios : Avoid fixture method explosion !

Assuming: working knowledge of Fitnesse.

I've been recommending Slim Scenarios for a while (primarily because they are the Fitnesse equivalent of reusable blocks (methods/functions in your favourite programming language) i.e. tables that can be called from other tables. {Actually they are akin to macro expansion.. but that's nitpicking!)

However soon I ran into a problem, the scenario steps translate into method calls onto the backing fixture class.
e.g.



|scenario |play movie|pathToMovie|on home theatre|
|enter |HDMI1 |mode on tv |
|enter |DTV/CBL |mode on avr |
|set avr volume to|-25 |dB |
|navigate menu to |@pathToMovie |
|press |play |on media player |


Now whenever I call this scenario, the fixture methods 'enterModeOnTv', 'enterModeOnAvr', etc. need to be present on the fixture class. So if Fixtures A, B, c call this scenario, All of them need these methods on them. Bummer!

Now the initial response was to extract these methods onto a helper class. Still I'd need to write some delegating methods on each fixture to delegate to the extracted class. So I raise my hand, admit my ignorance and post to the fitnesse forums. The experts answer in a flash!

The magic answer is the Library Table

FrontPage.HomeTheatreTests.SetUp

|library |
|television |
|avr |
|media player|


The Library table specifies a list of class that should be checked in case the fixture does not contain the required method. So in this case, the order in which the classes would be checked would be [Fixture > MediaPlayer > Avr > Television]. If a matching method is found in any of these classes, the step is resolved.. No more delegating methods!

This allows me to have cohesive helper classes that contain related methods which can be mixed into any page.

Another notable mention is ScenarioLibrary pages - these are pages which are libraries of usable scenarios.

FrontPage.HomeTheatreTests.ScenarioLibrary


|scenario |play movie|pathToMovie|on home theatre|
|enter |HDMI1 |mode on tv |
|enter |DTV/CBL |mode on avr |
|set avr volume to|-25 |dB |
|navigate menu to |@pathToMovie |
|press |play |on media player |

|scenario|start home theatre|
|power |on |media player |
|power |on |avr |
|power |on |tv |
...



ScenarioLibrary pages are included if they are a brother/uncle of the current page. Also all ScenarioLibrary pages up the hierarchy are included (allowing the possibility of overriding)

All this leads to very small test pages and it all works!

FrontPage.HomeTheatreTests.CanWorkWhileWatchingMovie


# ScenarioLibrary page is included (helper slim scenario definitions)
# Next SetUp page is included (imports and library tables)

|script |me |
|start home theatre |
|play movie|File Manager\USB\C\2 Watch\Iron Man 2|on home theatre|
|start working |
|after |30 |mins |
|ensure |work is done |
|press |stop |on media player|
|shut down home theatre |



In this example, the fixture Me only needs to have methods that pertain to me working. All methods related to the TV, AVR and MediaPlayer are resolved by the corresponding classes in the Fixture.dll due to the Library table.

public class Me
{
private bool _workIsDone ...

public void startWorking() ...
public void afterMins(int timeInMinutes) ...
public bool workIsDone ...
}

Pretty cool!

What do I use for acceptance tests (ATDD) : NUnit vs Fitnesse ?

Lately I've had some teams in my getting-agile ecosystem debating on which tool to use for acceptance testing. Now my first response is always "It depends" (You really can't go wrong with that. :) ).

Notation: I'm gonna use
  • NUnit when I actually mean any member of the xUnit family of unit-testing frameworks. 
  • Fit/Fitnesse stands for itself and now Slim/Fitnesse.
  • Customer means the XP's Customer role or Scrum's Product Owner role.

Fit-Fitnesse was the de-facto tool for automated acceptance tests till sometime ago.. Around 2009, there were strong murmurs that Fitnesse isn't working that well (read as some teams weren't executing very well and Fitnesse was part of their toolkit ).

So what does it "depend" on ??

How to get Thoughtworks' White to LogStructure

Struggled for some time getting it to work. I've been playing with Thoughtworks' open library for UI Testing for a while.

Sometimes UISpy doesn't get you to the UIElement hierarchy and you need to take out the big guns ala White's window.LogStructure to dump out the UIElement tree.
As always it's simple when you know how.

Step#1: Modify the app.config of your executable to include the sections related to White. See a sample file on White's page here.

Step#2: Add the following line to your AssemblyInfo.cs file

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]

Step#3: Add a file called Log4Net.config under your assembly (configure it such that it is always copied to the output folder). This contains the configuration information for Log4Net (e.g. the following config logs to console and to file named example.log in your output folder.). That's it you should now be able to see/capture window.LogStructure output from White. Godspeed !



<log4net>
  <appender name="Console" type="log4net.Appender.ConsoleAppender">
    <layout type="log4net.Layout.PatternLayout">
      <!-- Pattern to output the caller's file name and line number -->
      <conversionPattern value="%5level [%thread] (%file:%line) - %message%newline" />
    </layout>
  </appender>

  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <file value="example.log" />
    <appendToFile value="true" />
    <maximumFileSize value="100KB" />
    <maxSizeRollBackups value="2" />

    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%level %thread %logger - %message%newline" />
    </layout>
  </appender>

  <root>
    <level value="DEBUG" />
    <appender-ref ref="Console" />
    <appender-ref ref="RollingFile" />
  </root>
</log4net>

An effective test strategy to grow applications

This is a post to summarize my understanding (as of today) of an effective (low ceremony) way to build applications.
Let's take a look at (a slightly modified version) of Mike Cohn's layered test pyramid.



The choice of a pyramid indicates the robustness/stability of a lower layer directly affects the effectiveness of the upper layer. Also the number of tests decreases as you move up. As the agile testing book says ROI is maximum at the bottom (speed of feedback over time invested) and wanes towards the top.
e.g. without robust unit-tests, DSL tests or GUI tests would catch a bunch of errors without the essential feedback needed to fix it quickly. More and more errors would make it up to the middle and top layers, where it is more time-consuming/expensive to find-n-fix. Nothing replaces well-written, quick, professional unit tests.
To prevent ambiguity and misinterpretation, let's go over each layer.

Review : Growing Object Oriented Software - Guided by Tests: Freeman, Pryce

Recommended... best book on TDD in a while.

Just finished this one today... I got to fess up - that I am a "classicist". I've seen some real spaghetti tests involving mocks.. But I've gotten some periodic tension from the people on the other side of this religious fence of TDD. Since this book comes from "the torch-bearers of the mockist camp", I picked up a copy and tried to keep an open mind. And I although I haven't switched camps.. I now see the light. There is no one right path but the authors have placed some industrial strength beacons on this path and teach you how to use mocks and interaction tests to "grow" applications driven by automated tests. (However I still maintain that in untrained hands, Mocks (like C++) can be very dangerous and quickly lead into tarpits. Easy to abuse. However in the right hands, they can be used to write very expressive code & enable rapid and iterative development. ).

Some of the key takeaways for me were:
  • Developing outside-in ATDD: writing a 'walking skeleton' first , spotting objects and roles (relationships) between them, TDDing these objects and "folding them back" into a running app was a new method to me.
  • Listening to the tests, Focus on readability, tests with helpful diagnostics / failure messages, eliminating or reducing the irrelevant part of the test, use of builders + drivers to keep the tests concise
  • The chapters on threads and asynchronous testing are home-runs. Don't leave for work without it. The last third of the book was worth the price of the book (It isn't yet available in India so had to get it from overseas).
There is a lot of real world knowledge that the authors have distilled down to a kind of 'secret sauce'.

Contract Tests with Slim/Fitnesse : Running a test suite against multiple implementations of an interface

Recently I had a need for something similar to "xUnit contract tests" in Fitnesse (defined as: a test suite, which any object must satisfy so that it can be considered as a valid implementation of a Role. I got the term from one of J.B.Rainsberger's talks. )

To illustrate my point, let me cook up an example.

Imagine a contest for BoneyM impersonators. We would quiz each impersonator with a set of questions that they must answer correctly to win the contest.

i.e. we have a set of tests (questions) for each implementation of an Impersonator (Role). We also have multiple impersonators that I want to validate against the contract tests. The tests need to be dry - since they don't change for each implementation.

Implementing case-insensitive lookup tables (Dictionary) with string keys

The Dictionary type in .Net takes in a comparer as a constructor parameter. So you could pass in StringComparer.OrdinalIgnoreCase and you're done.
I used to upper-case keys while adding it to the lookup table earlier and again when performing a lookup - to achieve case-insensitive string lookups. I remember reading some article about String.ToUpper() being optimized for such scenarios. Now I was unsure - which one is better ?

WPF - Find a child control of a specific type or satisfying a given predicate under a parent control

Ideally you shouldn't be doing this in WPF and MVVM land. However there is an exception to every rule.. mine was I had to set the focus and put a specific cell in a grid into edit mode when the user clicked a button.

Set keyboard focus when the user begins editing a wpf datagrid templatecolumn ?

The problem:
When I begin editing a grid cell, I'd expect the keyboard focus to be set the edit control for the cell. In case of a textbox, I'd also like the existing contents to be selected by default ; so that i can begin typing and set a new value quickly.

Humanized's Enso Launcher : Jumpstart

Enso is a good example of the axiom that 'Search is faster than navigation'. Its one of the tools that I was introduced to by the book 'The productive programmer' by Neal Ford. It has been handy ever since.

The concept of the tool is pretty simple... it redefines the way in which you communicate with your machine. e.g. If I want to install or uninstall a program, I do not want to click through a number of windows and dig through menus (and lose my focus by the time I get there). My intention is 'open add or remove programs' so that I can install that new app. It may be a tiny boost but multiplied by the volume of instances / day, Enso can save you a lot of time. So lets get right to it...

First you need to install Humanized's Enso launcher (12 MB download)
Next it's easier if you are a keyboard person instead of a mouse person. You need some dexterity with your left pinky finger

Enso takes over your capslock key once installed. So keep capslock pressed down with your left pinky (you should see a green floating band at the top-left) and continue typing to issue commands....

Opening/Launching programs

With Vista and Windows7, this is not something to write home about. Both of them have a real-time search box when you invoke the Start Menu - where you can enter a substring/part of the app you want to invoke and the start menu narrows down your choices.

However if you're on WinXP, you're gonna love this. e.g I always had to go hunting for the add/remove programs applet inside the Start Menu. (or pick something else e.g. like a specific version of Visual Studio). Soon I'd be piling on quick launch icons ; and even that required you to reach for the mouse. (I like to be one with the keyboard as long as possible).

Now with enso, reach out your left pinky to the capslock key. Keep it pressed, while you continue to type a substring e.g 'open remove' or 'open 2008' in the green floating band that just popped up. You'll see a dynamically updating dropdown that you can use to select with the arrow keys. When you lift your finger off the capslock key. The selected program shall be opened. No kidding... try it. It's addictive ; No program is ever more than one open command away.
Useful: Absolutely

Associate a file/directory/url/shortcut with a command

Assume you have a directory that you frequently access e.g.
d:\mail\snail\wail\jail
Ensure that the above path is selected (either in the location bar of windows explorer or write it down in notepad and select it). Next use your pinky and type in
learn as open jail
Enso should get back with 'open jail is now a command'

Now try opening like before.
Caps + 'open jail'
and you should see a windows explorer window pointed at the right folder.

You just taught Enso a new command 'jail'.
You can verify this by looking in your MyDocuments folder. You should see a folder created by Enso with all your commands.
This also means that you can carry your enso commands with you across machine (e.g. in a USB storage device), dump it to the local MyDocuments folder and off you go.

Of course Enso just takes over your capslock key, to regain that function, Enso has 2 commands. Keep caps pressed and type
'capslock on' OR
'capslock off'.


You can make Enso unlearn a command by saying
Caps + 'unlearn open jail' Enso wipes its memory cells clean.
Useful: Usually. e.g. you could associate your MRU visual studio solution file with a command 'curproj'

Now try this on selected files/shortcuts.
e.g. Select any exe or shortcut in your file explorer.
Caps + learn as open someexe
Now you can the exe is at your fingertips with
'open somexe'
Works for shortcuts too. You can even create a "rooted view" e.g. create a shortcut for %windir%\explorer.exe /e, /root, D:\tarpit\theNextKillerApp
Select it and learn it as a command. Try it out
Useful: Sometimes

Works for urls as well. Enso would open up your a new instance/tab of your default browser pointed at the learned url.
e.g. select http://www.answers.com/topic/dexterity right here. Teach enso a new command
Caps + 'learn as open dex'
Now you can open this page at any time using
open dex

Useful: Occasionally - since browsers have generally better at this; bookmarks, tags and incremental search in the address bar.

Jump/Switch to an open window or tab in a browser

This one is nice.
Caps + 'go google'
or
go taskjump directly to an open window which has that substring in the window title.
Its works for browser tabs too - if you had a minimized or buried browser with a tab showing google's homepage, the right browser and child tab would be activated. Its a shame it doesn't work with Firefox3.. seems to be a bug that could be fixed. Works with IE8
Useful: Pretty much ; wish I could unlearn alt+tab-ing as easily as Enso.

Open with ...

This one is supereasy but hasn't become second nature to me yet. You can select any file (e.g. in a file explorer)
Caps + 'open with [name of app]'

and Enso does just that. e.g. 'open with notepad' will open up the selected file in notepad.
Useful: Yes. No more Shift+right click > Open with ... > hunt for the exe if !inList. Freedom!!

Close active window/tab

the command is close. I like dismissing windows with
Caps +'cl'
Enso can do minimize and maximise too.

For more inbuilt commands, Use Caps + 'command list' to have a look at inbuilt commands. I believe you can script custom commands too (e.g. 'mail' instead of 'open Outlook') if you know a bit of Python. However that's outside the scope of this post :)

That's all folks!

HOW TO : Setup your Xtreamer to stream content off Windows (Win7) machines via a wifi network

Update#2 [Apr 2010]: Sent the wireless USB dongle back to their seller in India since it was within the warranty period. They sent me a new dongle, free of cost. Now the whole setup is functional again. The online forum on the other hand was another deal altogether...

Update: My Xtreamer has stopped communicating via wifi after 3 days, without any configuration changes. "Can't get SSID" is the only response I get from the network settings page. The Wifi antenna drivers are proprietary (available for download) and hence I can't isolate the problem to the antenna. 2 subsequent posts to the Xtreamer forum have been mysteriously being deleted without any dialogue/clarification. Verdict as of now: Flaky antenna/connection finder.. wouldn't get this if streaming is your main need.

This post details my skirmishes in getting my Xtreamer (a streaming media player) to wirelessly stream content off my Windows7 laptop via a DLink N-Router. You could hook it up such that the Xtreamer can also access the internet - but I haven't done that. I intend to use the Xtreamer on a local trusted network and internet access on a diff public wireless network.

NUnit ExpectedException Bug in 2.4.7

"Bug In NUnit ? It can't be!" Exactly my words ; However it turned out that the behavior is due to a newer NUnit runner (Gui v 2.5.3) running a test fixture referencing an older version of NUnit.Framework.dll (v2.4.7)

Try this in a NUnit test fixture referencing NUnit.Framework v 2.4.7


// 2.4.7 - test passes even if an exception of wrong type is thrown
[ExpectedException(ExceptionType=typeof(FileNotFoundException))]
[Test]
public void Test_ExpectedException()
{
throw new ArgumentException();
}


I found that the test passes if "any" exception is thrown. It doesn't have to match the specified type. A false positive!

To fix this, upgrade your NUnit version to 2.5.2. You'd also need to fix a compile error. 'ExceptionType' property has now become ExpectedException.


//2.5.2 'works as expected'
[ExpectedException(ExpectedException=typeof(FileNotFoundException))]
[Test]
public void Test_ExpectedException()
{
throw new ArgumentException();
}



You live... you learn.

Method resolution in Ruby : OR how to find Mr. Right method?

Before I begin: Some of the stuff below may be incorrect (Corrections welcome.), however it helps me understand ruby method resolution. I have come up with this model based on my reading of the RubyProgrammingLanguage book (must-read for anyone learning Ruby) by Flanagan & Matz and some tinkering.. it may not be accurate (if that is what you're after)


Basket of Facts:
  • A Ruby type is an object of type 'Class' (henceforth referred to as a class-object)
  • An object has a class attribute pointing to the right class-object.
  • An object has an "eigenclass"/"metaclass" that holds singleton methods (methods that are only available to that instance.)

class-objects are special in a few ways:
  • a class-object has its class attribute pointing to the 'Class' type in Ruby
  • a class-object has a superclass
  • the "eigenclass" of a class-object also has a superclass; the eigenclass of its superclass
  • a class-object has an included modules list
  • a class-object has a table of methods (instance methods defined in the class definition)
  • class methods are singleton methods of the class-object
  • a class-object is generally associated with a constant viz. it's class name.



So now let's get started. Don't let the following mouse-drawn picture scare you - it'll all make (some?) sense in sometime. In the meantime, right click on it and open it up in a new tab and have the picture handy for reference while you descend into this post.



Next jump right over this big puddle of source code. You can copy it into your editor if you want to try it out with me..

module Kernel
def breadcrumb
puts "Kernel#breadcrumb"
Module.nesting[0].instance_eval{ remove_method :breadcrumb }
end
end
class Object
def breadcrumb
puts "Object#breadcrumb"
Module.nesting[0].instance_eval{ remove_method :breadcrumb }
end
def self.breadcrumb
puts "Object.breadcrumb"
class << Module.nesting[0]
instance_eval { remove_method :breadcrumb }
end
end
end

module MyModule
def breadcrumb
puts "MyModule#breadcrumb"
Module.nesting[0].instance_eval{ remove_method :breadcrumb }
end

end

class Base
MY_CONST = :b
include MyModule

def breadcrumb
puts "Base#breadcrumb";
Base.class_eval{ remove_method :breadcrumb }
# Base.instance_eval{ remove_method :breadcrumb } UH-OH! why does this remove the inst method
end
def self.breadcrumb
puts "Base.breadcrumb"
class << Module.nesting[0]
instance_eval{ remove_method :breadcrumb}
end
end
end

class Derived < Base
def breadcrumb
puts "Derived#breadcrumb";
Module.nesting[0].instance_eval{ remove_method :breadcrumb }
end
def self.breadcrumb
puts "Derived.breadcrumb"
class << self
instance_eval{ remove_method :breadcrumb}
end
end
end

class Class
def breadcrumb
puts "Class#breadcrumb";
Class.class_eval{ remove_method :breadcrumb }
end
end
class Module
def breadcrumb
puts "Module#breadcrumb";
Module.class_eval{ remove_method :breadcrumb }
end
end



****LANDING ZONE****
Nice Jump!

I have defined a new class called 'Derived' which derives from 'Base' and includes 'MyModule'.
Unless a base type is explicitly specified, all classes derive from Object (which includes Kernel) (and derives from BasicObject - new in Ruby 1.9). e.g. Base derives from Object. This can be verified via


d = Derived.new
p d.class.ancestors # => [Derived, Base, MyModule, Object, Kernel, BasicObject]



Base and Derived each have defined a class method (self.breadcrumb) and an instance method (breadcrumb). MyModule just defines a module method of the same name.
Convention: Class/Singleton methods would print receiver.breadcrumb. Instance methods would print receiver#breadcrumb.

Take a deep breath and dive in...

First lets create a new instance of Derived and add a singleton method to it. (i.e. a method that is present only in that instance. Another instance of Derived would not have this method)
Here's how we do that...


d = Derived.new

class << d
def breadcrumb
puts "DerivedObj[id:%d].breadcrumb" % object_id
class << self
instance_eval{ remove_method :breadcrumb}
end
end
end


'Call once': once the method is called, the method disappears (is 'undefined'). This will help us uncover the order in Ruby tries to find a method. I have added such methods in all types up the hierarchy (and then some) to help us spot the trail.
(Note: Instance methods use class_eval to remove themselves. Singleton/class methods use instance_eval. Refer to the RPL book)

And now for the moment of truth


puts "Method call on an object".center(40, "*")
6.times{ d.breadcrumb }


Output:
********Method call on an object********
DerivedObj[id:6186928].breadcrumb
Derived#breadcrumb
Base#breadcrumb
MyModule#breadcrumb
Object#breadcrumb
Kernel#breadcrumb


Refer to the image (I was reading Why's Nobody know Shoes; which might explain some of the weird imagery and the helpfulness of it all ;) So here's what happened in the sequence illustrated by our 'call-once' breadcrumbs:

To the extreme left is our object d,
  • Call1: Find the eigenclass of d, look for a singleton method of that name. Found!
  • Call2: .. not found in eigenclass, find the class-object of d via the class attribute. Look in the methods defined in class Derived. Found!
  • Call3: .. not found in eigenclass/class. Look in included modules of D (most recently included one first).. there are none. Travel via the superclass portal to reach Base. Look for inst method. Found!
  • Call4: .. not found in eigen/class/incl module/superclass. Try included modules of superclass e.g. MyModule. Found!
  • Call5: .. not found in eigen/class-n-its-modules/superclass-n-its-modules. Go down the superclass portal again to reach Object. Look at instance methods. Found!
  • Call6: .. look in incl. modules of Object. Kernel. Found!



If you try calling the method again, Ruby would not be able to find a method of that name and would now try looking for a method_missing method (in the same manner as it tried looking for breadcrumb. However this time it is guaranteed to find it because Kernel has a method_missing implementation that raises the NoMethodError. Need to see it to believe it?


temp.rb:84:in `block in
': undefined method `breadcrumb' for # (NoMethodError)
from temp.rb:84:in `times'
from temp.rb:84:in `
'


So lets recap the steps.
1. Look in the eigenclass (golden arrow) for the class
2. If not found, traverse the class attribute (purple arrow) to find the class-object.
3. Look in the instance methods for this class
4. If not found, try included modules of the class (in reverse order of mixin)
5. If not found, check if we have a superclass (pink arrow). If yes, repeat steps 3-5 till we run out of superclasses
6. If still not found, go back to Step1 but this time look for a 'method_missing' method'


By the way, we just saw how instance methods are inherited. (Snuck that one on you.) If Derived doesn't define an instance method, all its ancestors are looked up in order ; inheritance works.

Take a break, have some lemonade before we set out again... Ready? Off we go again. This time instead of calling a method on an object, we call a class method. Comment the previous 2 lines...


puts "Method call on a class-object".center(40, "*")
7.times{ Derived.breadcrumb }


Output:
*****Method call on a class-object******
Derived.breadcrumb
Base.breadcrumb
Object.breadcrumb
Class#breadcrumb
Module#breadcrumb
Object#breadcrumb
Kernel#breadcrumb


Hey! we see some instance methods being invoked when we call a class method. What the... Deep breaths 1..2..3..pfffhoooo (u got to get the pfffhoooo right)

Let's see if our image can help us out, find the object pointed to by the constant Derived (3rd box from the left - first row)

  • Call1: Start at Derived. Follow the golden arrow to the Derived's eigenclass - Derived". Look for a singleton method. Found!
  • Call2: .. not found in eigenclass. But eigenclasses of class-objects have superclasses. Follow the golden arrow to Base's eigenclass. Found!
  • Call3: .. not found in Derived" or Base". But we still have a golden arrow to Object". Found!
  • Call4: .. not found in Derived"/Base"/Object".Try BasicObject" too. Not found. Now we're out of superclasses. Now we follow the purple arrow to the class-object of Derived i.e. Class. Look for instance methods defined there. Found!
  • Call5: .. not found in the eigenclass hierarchy or class-object. Try included modules in Class. not found. But wait, we have a superclass. Down the pink arrow to Module. Look for an instance method... found!
  • Call6: .. not found in eigenclass hierarchy/Class-n-included-modules/Module. Try included modules in Module. Nope. Down the pink arrow to Object. Found an instance method!
  • Call7: .. not found in eigenclass hierarchy/Class-n-incl-modules/Module-n-incl-modules/Object. Look in included modules of Object.. aha Kernel. Look for method.. found!



If you make one more call, you should now be guessing that a NoMethodError should show up from Kernel#method_missing(similar to the previous example)

So lets refactor the steps.
  1. Look for the method in the eigenclass (yellow arrow). Until we run out of superclasses for the eigenclass, inspect each eigenclass for the method.
  2. If not found, traverse the class attribute (purple arrow) to find the class-object.
  3. Look in the instance methods for this class
  4. If not found, try included modules of the class (in reverse order of mixin)
  5. If not found, check if we have a superclass (pink arrow). If yes, repeat steps 3-5 till we run out of superclasses
  6. If still not found, go back to Step1 but this time look for a 'method_missing' method

So the only new tidbits were
  • class methods are singleton methods of class-objects. They live in the green clouds tied with the yellow arrows to the class.
  • eigenclass of a class-object is special. These special 'green clouds' have superclasses.
And that is the secret behind class method inheritance... See the first three lines of the output. (Snuck another one.. {snicker} No more I promise.)

And that also explains how class method calls can result in instance methods being called. (Lines4-7)

And that's it folks! You will wake up enlightened or confused when I snap my fingers :)


As an exercise to people who like to stay and flex some meta-programming muscles. Try and explain this predicament.

Module defines a constants method, which returns the list of all known constants (incl. class names).
Module.constants => 102
Any user-defined class e.g. Base or Derived inherits this method ; however Base.constants returns only the constants defined inside Base (and its superclasses). e.g. If I add a constant inside Base.
Base.constants => 1
How does Module's constants behave differently in the Base (which inherits this functionality)?

Hint: Check Module.singleton_methods and Module.public instance_methods
Hint2: Hit Stackoverflow and search for the answer once you have taken a good crack at it.

Meet the frameworks : Rhino v Moq v jMock : Part II

Story so far
We've seen how to
* setup expectations for calls on methods/properties.
* specify the number of times to be called.
* specify values to be returned

Now I move onto more involved scenarios.

#6:Throw an exception in response to an expected call on mockCollaborator.Method()
  • Rhino Mocks


[ExpectedException(ExceptionType=typeof(UnableToServeException),
MatchType=MessageMatch.Contains,
ExpectedMessage="Sorry for the inconvenience.")]
[Test]
public void Test_ExpectExceptionToBeThrown()
{
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, false)).Throw(new Exception());

_bakery.PlaceOrder(OrderForOnePineappleCakeNoIcing);
}

The Throw method tagged onto the end of the Expect does the trick of raising any derivation of Exception (here I've raised a generic Exception)
  • Moq


[ExpectedException(ExceptionType=typeof(UnableToServeException),
MatchType=MessageMatch.Contains,
ExpectedMessage="Sorry for the inconvenience.")]
[Test]
public void Test_ExpectExceptionToBeThrown()
{
_mockChef.Setup( chef => chef.Bake(CakeFlavors.Pineapple, false)).Throws<Exception>();
_bakery.PlaceOrder( OrderForOnePineappleCakeNoIcing );
}

Moq uses a generic Throws() to achieve the result
  • jMock


@Test
public void test_expectAndThrowException() throws OutOfIngredientsException
{
final Sequence aSequence = context.sequence("retryBake");
context.checking( new Expectations() {{
oneOf(_mockChef).bakeRealWorld( CakeFlavors.Pineapple, false );
will(throwException(new OutOfIngredientsException() ));
inSequence(aSequence);
oneOf(_mockInventory).replenishStocks();
inSequence(aSequence);
oneOf(_mockChef).bakeRealWorld( CakeFlavors.Pineapple, false );
inSequence(aSequence);
}});

_bakery.placeOrderRealWorld( OrderForOnePineappleCakeNoIcing() );
}

The will(throwException(exceptionInstance) after an expectation does the trick. Ignore the lines in Sequence (I'll get to them in Section#9)

Java's checked exceptions and explicit method specification (all the way up the call-chain) feels a bit too rigid to me (maybe due to my .Net exposure). So I've created an overload of Bake that throws an exception, to avoid adding a throws clause to every test method that has an expectation for Bake(). Worked for me.. although it's not the right thing to do. The joys of coding in a toy example!

void bakeRealWorld(CakeFlavors flavor, boolean withIcing) throws OutOfIngredientsException;


#7:Custom callbacks or blocks of code to execute when a mockCollaborator.Method() is called
Let me cook up a use for this. Let's say I want the first call to Chef.Bake throw an OutOfIngredientsException(), so that I can call ReplenishStocks() and retry. This time, the call to Chef.Bake should go through.

Just the kind of job for... custom Callbacks!

  • Rhino Mocks


[Test]
public void Test_ExpectWithCustomCallback()
{
int callbacks = 0;
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, false))
.Repeat.Times(2)
.WhenCalled(delegate(MethodInvocation mi) {
Console.WriteLine("Callback Params: {0}, {1}", mi.Arguments[0], mi.Arguments[1]);
callbacks += 1;
if (callbacks == 1)
throw new OutOfIngredientsException();

return;
});
_mockInventory.Expect(inv => inv.ReplenishStocks()).Return(true);

_bakery.PlaceOrder(OrderForOnePineappleCakeNoIcing);

_mockChef.VerifyAllExpectations();
_mockInventory.VerifyAllExpectations();
}

Tag on WhenCalled(delegateWithCustomCode) to the expectation. Also note that you have access to the method arguments as shown in the Console trace above.
  • Moq


[Test]
public void Test_ExpectWithCustomCallback()
{
var callbacks = 0;
_mockChef.Setup(chef => chef.Bake(CakeFlavors.Pineapple, false))
.Callback( delegate(CakeFlavors flavor, bool withIcing)
{ // any custom code
Console.WriteLine("Callback Params: {0}, {1}", flavor, withIcing);
callbacks += 1;
if (callbacks == 1)
throw new OutOfIngredientsException();

return;
}
);

_mockInventory.Setup(inv => inv.ReplenishStocks()).Returns(true);
_bakery.PlaceOrder( OrderForOnePineappleCakeNoIcing );

_mockChef.VerifyAll();
_mockInventory.VerifyAll();
}

Tag on an overload of Callback( customDelegate ) at the end of the Setup to specify custom code to be executed.
Moq gives you strongly typed callbacks with upto 4 parameters (Action is the biggest Action type in .Net; a restriction that will be lifted with .net 4.0). Argument access is a snap.

  • jMock


// http://www.jmock.org/custom-actions.html
@Test
public void test_expectAndInvokeCustomCallback()
{
context.checking( new Expectations() { {
oneOf(_mockChef).bake(CakeFlavors.Pineapple, false );
will( MyCustomCallback.tracingCallback() );
} } );

_bakery.placeOrder( new Order(CakeFlavors.Pineapple, false, 1) );
}
class MyCustomCallback implements Action
{
public void describeTo(org.hamcrest.Description description)
{
description.appendText("a custom callback to do what I deem fit! ");
}

public Object invoke(Invocation invocation) throws Throwable
{ // any custom code
System.out.println("Callback invoked with "
+ ((CakeFlavors)invocation.getParameter(0))
+ " and "
+ (((Boolean) invocation.getParameter(1)).booleanValue() ? "" : "no")
+ " icing!");
return null;
}
public static Action tracingCallback()
{
return new MyCustomCallback();
}
}

It may be due to my rusty Java but it turned out to be a whole lot of classes to achieve this with jMock

#8:Raise an event from a mock collaborator
This one is very handy when testing GUIs using a ModelViewPresenter (or related pattern)

Our inventory raises an event when we're running low on a particular ingredient. The bakery can use this notification to tell the Chef to go easy on that ingredient, while we stock our supplies.

  • Rhino Mocks


[Test]
public void Test_RaiseEventFromMock()
{
_mockChef.Expect(chef => chef.GoEasyOn("Sugar"));

_mockInventory.Raise(inv => inv.RunningLowOnIngredient += null,
this, new StockEventArgs("Sugar"));

_mockChef.VerifyAllExpectations();
}

To raise an event, invoke the Raise method on the mock with a null subscription to the event & the arguments to be passed onto the event handler method.
  • Moq


[Test]
public void Test_RaiseEventFromMock()
{
_mockChef.Setup(chef => chef.GoEasyOn("Sugar"));

_mockInventory.Raise(inventory => inventory.RunningLowOnIngredient += null, new StockEventArgs("Sugar"));
_mockChef.VerifyAll();
}

Identical to Rhino except for the fact that you don't have to specify the 'sender' parameter.
  • jMock

Java doesn't support events as first-class citizens. You need to manually implement the publisher-subscriber pattern.

#9:Argument Constraints
Sometimes, we do not want to / cannot specify the exact arguments with which a method on a collaborator will be called as part of the expectation. In such cases, we use constraints on the arguments, which must be met for the expectation to be met.
e.g. from the previous example, lets say we don't know the value of the Low-stock-ingredient at compile-time. We have a variable into which we can fetch the ingredient and which we can use to compare against the actual value.
In short we want to specify a Predicate (a function which returns true/false) for an argument as a constraint.

  • Rhino Mocks


[Test]
public void Test_ConstrainingArguments()
{
var itemAboutToGoOutOfStock = "Eggs";
_mockChef.Expect(chef => chef.GoEasyOn(
Arg<string>.Matches (ingredient => ComplexCheck(itemAboutToGoOutOfStock, ingredient))));

_mockInventory.Raise(inventory => inventory.RunningLowOnIngredient += null,
this, new StockEventArgs(itemAboutToGoOutOfStock));
_mockChef.VerifyAllExpectations();
}
private bool ComplexCheck(string expected, string actual)
{
return expected.Equals(actual); // any complex test
}

So here we use Arg.Matches(predicate) to do a complex constraint on the string argument for Chef#GoEasyOn(). There are a bunch of other helpful constraints - explore the Arg type docs (or the intellisense popup) for more.
  • Moq


[Test]
public void Test_ConstrainingArguments()
{
var itemAboutToGoOutOfStock = "Eggs";
_mockChef.Setup(chef => chef.GoEasyOn(
It.Is<string>(ingredient => ComplexCheck(itemAboutToGoOutOfStock, ingredient))));

_mockInventory.Raise(inventory => inventory.RunningLowOnIngredient += null,
new StockEventArgs(itemAboutToGoOutOfStock));
_mockChef.VerifyAll();
}
private bool ComplexCheck(string expected, string actual)
{
return expected.Equals(actual); // any complex test
}

Moq has It.Is(predicate) for this purpose. Explore the type documentation (or the intellisense popup) for more helper constraints.
  • jMock

The example is different. Here we are constraining the arguments to the Bake call with a predicate.

//http://www.jmock.org/custom-matchers.html
@Test
public void test_expectAndCheckArgs()
{
context.checking( new Expectations() { {
oneOf(_mockInventory).isEmpty();
will(returnValue(false));
oneOf(_mockChef).bake(
with( FlavorMatcher.aPineappleFlavoredCake() ),
with( any(boolean.class)));
}} );
_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}


class FlavorMatcher extends TypeSafeMatcher<CakeFlavors>
{
public boolean matchesSafely(CakeFlavors flavor)
{ // any complex test

return flavor == CakeFlavors.Pineapple;

}
public void describeTo(org.hamcrest.Description description) {
description.appendText("a cake with pineapple flavor ");
}

@Factory
public static Matcher<CakeFlavors> aPineappleFlavoredCake()
{
return new FlavorMatcher();
}
}

once again more classes than I'd liked (Disclaimer: rusty java programmer could be the problem).

Use with(matcherInstance) in place of arguments in the expectation. Derive a new Matcher derived class with your custom check.


#9:Expect a sequence of calls in a specific order
Ordered Expectations: Looking at the test in Section#4 - the test can be satisfied by the following implementation

public void PleaseDonate(Order order)
{
_chef.Bake(order.Flavor, order.WithIcing);
var isEmpty = _inventory.IsEmpty;
}

which is not what we were getting at. Seems like the test is missing something... the order of calls! Chef.Bake should be called after Inventory.IsEmpty.
  • Rhino Mocks


[Test]
public void Test_ExpectCallsInOrder()
{
var mockCreator = new MockRepository();
_mockChef = mockCreator.DynamicMock<Chef>();
_mockInventory = mockCreator.DynamicMock<Inventory>();
mockCreator.ReplayAll(); // to avoid setting up an expect for an event handler subscribe in the following ctor.

_bakery = new Bakery(_mockChef, _mockInventory);

using (mockCreator.Ordered())
{
_mockInventory.Expect(inv => inv.IsEmpty).Return(false);
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, false));
}

_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

_mockChef.VerifyAllExpectations();
_mockInventory.VerifyAllExpectations();
}


Woooaah! What just happened? Have a seat ; take a deep breath.
Ordered expectations have been a feature of Rhino Mocks; however the v3.5 syntax revamp hasn't made an impact here. This took some doing .. Turns out you need to go old-skool for a bit.
The key:
* Create a new MockRepository instance and invoke the DynamicMock method (instead of the static MockRepository.GenerateMock )
* Use the Ordered block to setup expectations in a specific order

  • Moq


[Test]
public void Test_ExpectCallsInOrder()
{
var sequence = String.Empty;
_mockInventory.Setup(inv => inv.IsEmpty).Returns(false)
.Callback(delegate { sequence += "1"; });
_mockChef.Setup(chef => chef.Bake(CakeFlavors.Pineapple, false))
.Callback(delegate { sequence += "2"; });

_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

Assert.AreEqual("12", sequence, "Calls not in expected order!");
_mockChef.VerifyAll();
_mockInventory.VerifyAll();
}

Last time I checked (Jan25,2010) Moq does not support this out of the box. However you could work around this with a collecting object. Very naive.. you could come up with better solutions to fit your exact context.
  • jMock


@Test
public void test_expectCallsInSpecificOrder()
{
final Sequence pleaseDonateSequence = context.sequence("pleaseDonate");
context.checking( new Expectations() {{
oneOf(_mockInventory).isEmpty();
inSequence(pleaseDonateSequence);
will(returnValue(false));
oneOf(_mockChef).bake(CakeFlavors.Pineapple, false);
inSequence(pleaseDonateSequence);
}});

_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}

jMock has the shortest syntax for ordered expectations. You create a named Sequence object and then tag the name along with each expectation (listed in the expected order).

So there you have it. If it was a showdown, jMock would be ahead of Moq and Rhino Mocks would be just a sliver behind Moq.

JMock:
+ has a nice readable concise API for number of invocations and ordered expectations

Moq:
+ has a nice mechanism for type-safe custom callbacks and argument constraints

Rhino:
+ isn't bad. Does everything. However even with the v3.5 syntax revamp, it is a little unintuitive as compared to the others. The documentation was a bit noob-unfriendly, when I needed it. However it is the only option if can't use .net 3.5 for your tests (which should be rare).

Meet the frameworks : Rhino Mocks v Moq v jMock : Part 1

If you've been near any TDD-infected person, you're sure to have heard about Mock frameworks (or served as a by-standing casualty in a classicist v Mockist skirmish). Then you have to look. At first you're apprehensive, it looks like too much work (defining interfaces, creating mocks, expectations, et. all). Soon you're cornered by a Data Access object or a Network stream and you have no choice. You dip your feet into the pool of mocks.. soon enough you're splashing around like a silly kid creating mocks willy-nilly (they're free). Unknown to you, the pool has some whirlpools that suck you in when you're having too much fun and not paying any attention. In the end, it's like mock-Children of the Corn..

I'm a sucker for horror stories (and there's that other little matter of being biased towards state-based tests.) As with most things, there is more than one way to use a tool - mock frameworks are no exception. The folks at mockobjects.com have a new book out which explains the right way (not read it yet; maybe I'll still be converted into a mockist.)

Personally my pet-peeve with mock frameworks has been the learning curve. Usually you don't have a dedicated time-slot to learn a mock framework (and that's kind of a good constraint since the mock frameworks are flexible, powerful and consequently huge); I'd bet that most of us learn them while trying to get a test to pass. Nothing like a reluctant mock framework with cryptic error messages between you and a green bar, to get you into real-curse-practice. The only thing that comes a distant second is "Which is better? Rhino Mocks or Moq ?" from people who haven't explored either of them. If both of them scratch your itch, take a pick!

So I've tried to list down the most probable scenarios and try each of them with RhinoMocks, Moq and jMock (always wanted to write some tests in jUnit).

  1. Expect a Call on mockCollaborator.method()
  2. Expect a call on mockCollaborator.getProperty and return something
  3. Expect n calls to mockCollaborator.Method()
  4. Return values from mockCollaborator.Method()
  5. Expect no call (Don't call me!)
  6. Throw an exception in response to an expected call on mockCollaborator.Method()
  7. Custom callbacks or blocks of code to execute when a mockCollaborator.Method() is called
  8. Raise an event from a mock collaborator
  9. Argument Constraints
  10. Expect a sequence of calls in a specific order
You could use this to make your own choice (which is only yours to make). I've written this down as a self-reference for the next time I'm wondering "Why doesn't this @#&*(@ test fail?' or 'How is this test passing?'

A template for interaction-tests



For state-based tests, I'd usually write my assert first, step back to the action that will lead to the assert and finally arranging everything for the test to work. However this doesn't exactly work for interaction-based tests: In this realm, it's more helpful to write the action first, then the expectations and other steps for arrange and finally assert (which sometimes is just verifying that the expected mocks were called. Some frameworks like jMock do it automatically at the end of the test.)
Arrange
  1. create mock objects for collaborators that you want to mock( not Stub. I hope you've read Martin Fowler's paper [link] on the difference.)
  2. Create your test subject (here a Bakery type) and inject the mock collaborators via ctor/setter methods.
  3. Define the interaction via 'expects'. e.g. I expect the test subject to call methodX on collaboratorA with these parameters.
Act
  1. State the action/behavior that is the primary focus of this test
Assert
  1. Assert any state-change (if applicable)
  2. Verify all expected calls on the collaborators were called.


Source Code:
The source code for this series is available for browse/checkout (you'll need subversion to checkout) at
Dot Net code
Java code

#1: Expect a Call on mockCollaborator.method()
  • Rhino v3.5 (with NUnit 2.4.8)


Let's see how we do this in Rhino Mocks 3.5 - use the above section to work through this example.
Rhino mocks has changed with a (IMHO noob-friendly/simpler) syntax with version 3.5 - Prior to that an explicit record-replay style was the norm. So if you're using a prior version, try moving to v3.5. (There is a forsaken commented-out source file in the above mentioned link for old-skool Rhino).

To declare that you expect a method to be called, you use the Expect method on the respective mock object. Lambda expressions, Generics and type-inference result in compile-time checks and Intellisense guiding you all the way.
The below expectation reads "On the mockChef, expect Bake to be called with Vanilla and false as arguments." (when someone calls PlaceOrder() on the bakery, which employs the Chef)
I'm not going to post the code to make this pass inline (for honoring the memory of brevity in blog posts). I suggest you try TDDing your way through like me / refer to the source repository.



[Test]
public void Test_ExpectMethodCall()
{ // arrange : create mocks
var mockChef = MockRepository.GenerateMock<Chef>();

// arrange: inject dependencies
Bakery bakery = new Bakery(mockChef);
// arrange: expect the Bake method on Chef to be called
mockChef.Expect(chef => chef.Bake(CakeFlavors.Vanilla, false));

//act
bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Vanilla, WithIcing = false, Quantity = 1 });

//assert
mockChef.VerifyAllExpectations();
}
  • Moq v 2.0.5 (with NUnit 2.4.8)
Moq was the new kid on the block challenging the leading .Net mock frameworks with .Net3.5 lambda-expressions powered snappy syntax.



[Test]
public void Test_ExpectMethodCall()
{
//arrange
var mockChef = new Mock<Chef>();

//arrange: inject dep
var bakery = new Bakery(mockChef.Object);
// arrange: expect
_mockChef.Setup(chef => chef.Bake(CakeFlavors.Vanilla, true));

//act
_bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Vanilla, WithIcing = true, Quantity = 1 });
//assert
_mockChef.VerifyAll();
}

Differences
#1: mockChef.Object is the mock collaborator; this is a common stumble for people new to Moq. I think (unverified) this is due to Moq's design of not having a different Repository or Mockery type.
#2: Moq uses Setup for expecations (instead of Rhino's Expect)

  • jMock 2.5.1 (with jUnit 4.8.1)

jMock is the Java mock framework distilled from the experience of the gurus at mockobjects.com ; they have a new book out and are the recognized pioneers of the "Mock objects" technique. I highly recommend their second revision of the acclaimed 'Mock Roles not objects' paper.
So let's see how the test looks like in jMock:


Mockery context = new JUnit4Mockery();

@Test
public void test_expectCall()
{
Chef mockChef = context.mock(Chef.class);
Bakery bakery = new Bakery(mockChef);

context.checking( new Expectations() { {
oneOf(mockChef).bake(CakeFlavors.Pineapple, false );
} } );

bakery.placeOrder( new Order(CakeFlavors.Pineapple, false, 1) );
// mockChef.Verify() - autoverified : framework :)
}


Differences
#1: jMock has a more fluent approach to specifying expectations - look inside the Expectations creation. It reads 'Expect one invocation on mockChef of method bake with parameters Pineapple and false. Refer to the nicely written jMock cheatsheet in case you're feeling a bit lost.
#2: You don't need to explicitly verify expectations - automatically done at the end of a test case.


#2 Expect a call on mockCollaborator.getProperty and return something
I've factored out common code into a SetUp method to shorten the code snippets. In general, .Net properties = one get_property method + one set_property method + one backing field. Syntactic sugar!

So when someone queries Bakery.IsOpen, check to see if the Chef is available.

  • Rhino Mocks


[Test]
public void Test_ExpectPropertyGet()
{
_mockChef.Expect(chef => chef.IsAvailable).Return(true);
Assert.IsTrue(_bakery.IsOpen);

_mockChef.Expect(chef => chef.IsAvailable).Return(false);
Assert.IsFalse(_bakery.IsOpen);

_mockChef.VerifyAllExpectations();
}


Note the new Return method tagging along with the Expect to signify what should be returned when the Bakery makes a call to Chef#IsAvailable
  • Moq


[Test]
public void Test_ExpectPropertyGet()
{
_mockChef.Setup(chef => chef.IsAvailable).Returns(true);
Assert.IsTrue(_bakery.IsOpen);

_mockChef.Setup(chef => chef.IsAvailable).Returns(false);
Assert.IsFalse(_bakery.IsOpen);

_mockChef.VerifyAll();
}

Moq calls it Returns which IMHO reads better.
  • jMock

Java does not have properties as first class language features. They are manually implemented as accessor/mutator method pair and a backing field.

#3: Expect n calls to mockCollaborator.Method()
So if I place an Order for 3 Pineapple cakes, I'd expect the Chef#Bake to be called thrice.
  • Rhino Mocks


[Test]
public void Test_ExpectMultipleCalls()
{
_mockChef.Expect(chef => chef.Bake(CakeFlavors.Pineapple, true)).Repeat.Times(3);

_bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Pineapple, WithIcing = true, Quantity = 3 });

_mockChef.VerifyAllExpectations();
}

Tag on the Repeat property to the Expect if you expect it to be called n times.
Caveat: the test fails if the mock isn't called at least 3 times. If you call it 3 or more times, the test passes. So if you have a need for exactly thrice, dive into the rhino mocks docs and let me know if you figure out a way to make it work.
  • Moq


[Test]
public void Test_ExpectMultipleMethodCalls()
{
_bakery.PlaceOrder(new Order { Flavor = CakeFlavors.Pineapple, WithIcing = false, Quantity = 3 });
_mockChef.Verify( chef => chef.Bake(CakeFlavors.Pineapple, false), Times.Exactly(3), "Chef should have been called thrice!");
}


Differences:
#1. With Moq, you specify this during verification with an overload of Verify (as opposed to while defining expectations)
#2 This test will pass only if Bake is called Exactly thrice (unlike Rhino)

  • jMock


@Test
public void test_expectMultipleCalls()
{
context.checking( new Expectations() {{
exactly(3).of(_mockChef).bake(CakeFlavors.Pineapple, false);
}} );

_bakery.placeOrder( new Order(CakeFlavors.Pineapple, false, 3) );
}

jMock wins this one for readabililty.
#4: Return values from mockCollaborator.Method()

Refer to #2 for Rhino and Moq. You tag on a Return/Returns method call to the expectation.
Let's say the bakery being a charitable organization, responds to a PleaseDonate message at the end of the day from cake-loving orphans. The bakery will ask the Chef to bake one for them after checking to see if they have surplus stocks in inventory.

  • jMock


@Test
public void test_expectCallAndReturnValue()
{
context.checking( new Expectations() {{
oneOf(_mockInventory).isEmpty();
will(returnValue(false));
oneOf(_mockChef).bake(CakeFlavors.Pineapple, false);
}} );

_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}

jMock has a will method to signify what will happen when the method is invoked. Use the indentation (convention) so that it reads better.

#5:Expect no call (Don't call me!)
When the orphans send a PleaseDonate() and there are no surplus stocks in inventory, you wouldn't want to bother the overworked chef at the end of a weary day.
  • Rhino Mocks


[Test]
public void Test_ExpectNoCall()
{
_mockInventory.Expect(inv => inv.IsEmpty).Return(true);
_mockChef.Expect(chef => chef.Bake(Arg<CakeFlavors>.Is.Anything, Arg<bool>.Is.Anything))
.Repeat.Never();

_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

_mockInventory.VerifyAllExpectations();
_mockChef.VerifyAllExpectations();
}

Note: This snippet gives you a sneak peek of Argument Constraints. In short the second line states 'mockChef#Bake should not be called (irrespective of arguments)' Bring the .Repeat.Never() clause into plain view by placing it on a new line with one level of indentation.
  • Moq


[Test]
public void Test_ExpectNoCall()
{
_mockInventory.Setup(inventory => inventory.IsEmpty).Returns(true);
_bakery.PleaseDonate(OrderForOnePineappleCakeNoIcing);

_mockChef.Verify(chef => chef.Bake(It.IsAny<CakeFlavors>(), It.IsAny<bool>()), Times.Never());
_mockInventory.VerifyAll();
}

Differences:
#1 Moq takes a different path of leaving the invocation-count check till the very end. Use the Verify Overload with Times.Never() as in Section#3
#2 Argument constaints in Moq read slightly better than Rhino.

  • jMock


@Test
public void test_expectNoCall()
{
context.checking( new Expectations() {{
oneOf(_mockInventory).isEmpty();
will(returnValue(true));
never(_mockChef).bake( CakeFlavors.Pineapple, false );

}});

_bakery.pleaseDonate( OrderForOnePineappleCakeNoIcing() );
}

jMock doesn't hide intent with never() leading the expectation. jMock's API shows the thought that's been put into it.

5 down. 5 for the next part.