-
-
Save kevinpet/2360519 to your computer and use it in GitHub Desktop.
Nullery: self-aware nulls for testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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