Test improvements

Previously, the test code was very verbose and very brittle.  This
change simplifies the main code by extracting out some common,
stubbable, methods which leads to much better testability.
Merge branch 'test-improvements'