Wednesday, September 16, 2009

Creating an Easy Mock Custom Matcher

This blog isn't really supposed to contain "how-to" entries (it's really just a place for me to vent). However, in the past I've found certain tasks worth putting somewhere online in case I need them in the future. I've used planet-source-code for snippets, sourceforge for projects, and maybe a few other sites here and there. Custom matchers in Easy Mock are just hard enough to want a reliable tutorial. While there may be better posts about this same subject elsewhere, there's something about reading code you've written to remind you how to write more code!

So, here's my "CollectionMatcher" class:

package project.test.common;

import java.util.Collection;

import org.easymock.IArgumentMatcher;
import org.easymock.classextension.EasyMock;

public class CollectionMatcher implements IArgumentMatcher {

private Collection collection;
private String notFound;

public CollectionMatcher(Collection collection) {
this.collection = collection;
notFound = "";
}

public static Collection collectionEq (Collection collection) {
EasyMock.reportMatcher(new CollectionMatcher(collection));
return null;
}

public void appendTo(StringBuffer buffer) {
buffer.append(notFound).append(" not found in {");

String comma = "";
for (Object o : collection) {
buffer.append(comma).append(o.toString());
comma = ",";
}

buffer.append("}");
}

public boolean matches(Object otherCollection) {
if (!(otherCollection instanceof Collection)) {
return false;
}

Collection otherText = (Collection)otherCollection;

for (Object o : otherText) {
if (!collection.contains(o)) {
notFound = o.toString();
return false;
}
}

return true;

}

}


So, now we can do things like:

package com.project.api.delivery;

import static project.test.common.CollectionMatcher.*;
import static org.easymock.classextension.EasyMock.*;

//other imports

public class PreviewCommandTest extends TestCase {

init(new PreviewCommand(preview));

{
ContentReplacementManager manager = managerContext.getContentReplacementManager();
expect(manager.replaceValues(content, null)).andReturn(content);
expect(manager.replaceTags(eq(content), (Preview)eq(null), (Collection)collectionEq(entity.getPreviews()))).andReturn(content);
managerContext.doReplay();
}

command.invoke(webContext);

managerContext.doVerify();

}

}

No comments:

Post a Comment