Jackrabbit and Mockito
I've been writing some code that talks to Jackrabbit, and wanted to write some tests.
Testing this sort of thing has traditionally been fairly difficult, because so much of your code is just calls into Jackrabbit. You'd need to create a lot of mock objects to mock the Jackrabbit side of the test, often leading to tests that are bigger than the code being tested!
Enter Mockito.
So you want to test some code that walks the children of a node in the repository? Simple. Here's an example:
[cc lang="java"]
// Create a mock repository, and when login is called with any
// SimpleCredentials instance, return a mock session.
Repository mockRepo = mock(Repository.class);
Session mockSession = mock(Session.class);
when (mockRepo.login(any(SimpleCredentials.class))).thenReturn(mockSession);
// Mock the root node, and have the session return it on request.
Node mockRootNode = mock(Node.class);
when (mockSession.getNode(eq("/content/myroot"))).thenReturn(mockRootNode);
// Mock two child nodes
Node mockNodeOne = mock(Node.class);
when (mockNodeOne.getName()).thenReturn("NodeOne");
Node mockNodeTwo = mock(Node.class);
when (mockNodeOne.getName()).thenReturn("NodeTwo");
// Mock an iterator that returns these two nodes
NodeIterator mockNodeIterator = mock(NodeIterator.class);
when (mockNodeIterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false);
when (mockNodeIterator.nextNode()).thenReturn(mockNodeOne).thenReturn(mockNodeTwo);
// When getNodes() is called on the root node, return the iterator
when (mockRootNode.getNodes()).thenReturn(mockNodeIterator);
// Now call into the code to be tested with the mock Repository.
codeToBeTested(mockRepo);
[/cc]
And if you're using Maven to build (I've become a huge Maven fan) then you can integrate Mockito simply by adding a dependency to your pom. Details are on the Mockito site.