Self Shunt Pattern

Let's say that you are a test case. One of the things you can do is pass yourself to the objects you are testing to get more information.

Rather than use the SelfShuntPattern, it might be just as easy, and more clear, to define an instance of the ShuntPattern or MockObject right there in your test method. Then, each method may use a different variation of the "shunt" appropriate for whatever is being tested. StevenNewton provided this example:
I HaveThisPattern, but in a slightly different implementation than described in the above paper. Inner classes (either anonymous or not) can serve as your shunt for classes you would like to test but you can't because your test already extends TestCase. The example in the above referenced paper like so:

 public class ScannerTest extends TestCase implements Display {

can be written like so in the case where Display (or whatever cooperating behavior you have to fake) is a class rather than an interface:

 public class ScannerTest extends TestCase {
	public class MockDisplay extends Display {
	 void displayItem (Item item) {
		// implementation elided

public void testScan() { Scanner scanner = new Scanner(new MockDisplay()); ..... } }
Perhaps this is reaching too far into the Java bag of tricks, but sometimes it's the only way to do it when you need "extends" instead of "implements".


That's conservative, actually. I frequently use the following :

	public void testScan() {
	Scanner scanner = new Scanner(new Display() {
		public void displayItem (Item item) {}
	// etc.

when I only need it for the current test. I extract the Mock later if I find myself tempted to copy/paste the original test. (Sometimes I extract the Mock after giving in to temptation, with two or three copies of the anonymous inner class already lying around.)

-- LaurentBossavit

[CategoryMockObjects] MockStubShunt

View edit of May 1, 2005 or FindPage with title or text search