Skip to content

Instantly share code, notes, and snippets.

Created March 29, 2012 22:50
Show Gist options
  • Save anonymous/2244577 to your computer and use it in GitHub Desktop.
Save anonymous/2244577 to your computer and use it in GitHub Desktop.
Nullery: self-aware nulls for testing
public class Nullery {
private static MockObjectNamingScheme namingScheme = new CamelCaseNamingScheme();
private static Imposteriser imposteriser = ClassImposteriser.INSTANCE;
public static <T> T nulled(Class<T> typeToNull) {
return nulled(typeToNull, namingScheme.defaultNameFor(typeToNull));
}
public static <T> T nulled(Class<T> typeToMock, final String name) {
Invokable invokable = new Invokable() {
@Override
public Object invoke(Invocation invocation) throws Throwable {
throw new NullPointerException(format("Called %s#%s", name, invocation.getInvokedMethod()
.getName()));
}
};
return imposteriser.imposterise(invokable, typeToMock, CaptureControl.class);
}
}
interface Invokable {
void invoke();
}
static class Invoker {
Invokable invokable;
Invoker(Invokable invokable) {
this.invokable = invokable;
}
void process() {
invokable.invoke();
}
}
@Test
public void shouldThrowNpeWithGoodMessage() {
Invokable nullInvokable = Nullery.nulled(Invokable.class);
Invoker invoker = new Invoker(nullInvokable);
try {
invoker.process();
fail("Expected a NPE");
} catch (NullPointerException npe) {
npe.printStackTrace();
assertThat(npe.getMessage(), Matchers.containsString("invokable#invoke"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment