« Seven Languages in Seven Weeks | Main | Four Fish »

Capture an Argument Matcher

More than once I've found myself writing unit test code for a class that internally constructs an object which is then passed along to another method. A common pattern would be to introduce a factory for this internally created object, but at times this feels too heavy weight. I'd still like to make a few assertions about the object but this can get tricky when using lots of mock objects. Enter a little utility class called CaptureArgument. It is a type safe matcher that, wait for it, captures the argument it matched which allows you to inspect it. You can grab a copy of the class at GitHub. Below is a sample usage:

final MBeanServer mBeanServer = context.mock(MBeanServer.class);
final Object objectToRegister = new Object();
final CaptureArgument<ObjectName> captureArgument = new CaptureArgument<ObjectName>();
context.checking(new Expectations() {{
        oneOf(mBeanServer).registerMBean(with(same(objectToRegister)), with(captureArgument));
    }});
unitUnderTest.doSomething(objectToRegister);
assertEquals("BeanDomain", captureArgument.getArgument().getDomain());

Tags: java junit