Last active
December 12, 2015 03:28
-
-
Save npryce/4706923 to your computer and use it in GitHub Desktop.
Noisy threading policy for jMock
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
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