Skip to content

Instantly share code, notes, and snippets.

@kevinpet
Forked from anonymous/Nullery.java
Created April 11, 2012 16:57
Show Gist options
  • Save kevinpet/2360519 to your computer and use it in GitHub Desktop.
Save kevinpet/2360519 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 {
NullPointerException npe = new NullPointerException(format("Called %s#%s", name, invocation.getInvokedMethod().getName()));
StackTraceElement[] trace = npe.getStackTrace();
npe.setStackTrace(Arrays.copyOfRange(trace, 3, trace.length));
throw npe;
}
};
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