Skip to content

Instantly share code, notes, and snippets.

@npryce
Last active December 12, 2015 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save npryce/4706923 to your computer and use it in GitHub Desktop.
Save npryce/4706923 to your computer and use it in GitHub Desktop.
Noisy threading policy for jMock
private static class NoisyThreadingPolicy implements ThreadingPolicy
{
private final Thread testThread = Thread.currentThread();
@Override public Invokable synchroniseAccessTo(final Invokable mockObject)
{
final StackTraceElement[] creationStack = stackTrace();
return new Invokable()
{
@Override public Object invoke(Invocation invocation) throws Throwable
{
checkRunningOnTestThread();
return mockObject.invoke(invocation);
}
private void checkRunningOnTestThread()
{
Thread thread = Thread.currentThread();
if (thread != testThread)
{
final StackTraceElement[] invocationStack = stackTrace();
System.err.println("the Mockery is (deliberately) not thread-safe but mock object <" +
mockObject.toString() + "> was called on thread " +
thread.getName() + " (id=" + thread.getId() + ")");
dumpStackTrace(mockObject.toString() + " created here:", creationStack);
dumpStackTrace(mockObject.toString() + " invoked here:", invocationStack);
throw new ConcurrentModificationException("on wrong thread");
}
}
};
}
private StackTraceElement[] stackTrace()
{
return new Exception().getStackTrace();
}
private void dumpStackTrace(String s, StackTraceElement[] stack)
{
System.err.println(s);
for (StackTraceElement stackTraceElement : stack)
{
if (!isFromTestFramework(stackTraceElement))
{
System.err.println(" " + stackTraceElement.toString());
}
}
}
private boolean isFromTestFramework(StackTraceElement element)
{
String className = element.getClassName();
return className.startsWith(getClass().getName())
|| className.startsWith("org.junit")
|| className.startsWith("junit.framework")
|| className.startsWith("org.jmock")
|| className.startsWith("sun.reflect")
|| className.startsWith("java.lang.reflect.Constructor")
|| className.startsWith("org.apache.tools.ant.taskdefs.optional.junit");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment