Genericize for Testability

Paul Brown @ 2006-06-17T03:19:00Z

I needed an algorithm to traverse a graph of relationships and test whether it was a connected tree or not, so I coded-up a quick (and relatively efficient) search. No matter how many times I code graph searches, I know myself well enough to expect a couple of mistakes, so I went to write some tests after I'd finished with the algorithm. The reason that I'd put off writing the tests was that the signature for my search was the following:

static FancyIface findRoot(Map<FancyIface,FancyIface[]> graph)

FancyIface is an interface with a bazillion methods and where the API doesn't expose any implementations. Rather than mocking instances of FancyIface for testing purposes, it makes sense to genericize the method:

static <T> T findRoot(Map<T,T[]> graph)

and then code the tests with something nice and simple, like integers:

public void testFindRoot() {
  Map<Integer,Integer[]> m = new HashMap<Integer,Integer[]>();
  m.put(1,new Integer[] {2,3});
  m.put(2,new Integer[] {4});
  // should return 1, as this is a tree rooted at 1.
  assertTrue(Foo.findRoot(m) == 1);
  m.put(3,new Integer[] {4});
  // should return null because this is no longer a tree.
  assertFalse(Foo.findRoot(m) == null);
}

And that's it.

Meta

Tags: (tag) (tag) (tag)

(comment bubbles) 0 comments
265 direct views