Skip to content

Instantly share code, notes, and snippets.

@acdcjunior
Created January 23, 2016 23:36
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save acdcjunior/dce6dc4a948766596663 to your computer and use it in GitHub Desktop.
Save acdcjunior/dce6dc4a948766596663 to your computer and use it in GitHub Desktop.
Mockito: create a mock object that throws exception at any method call (so... a Dummy object, not a mock)
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;
import static org.mockito.Mockito.mock;
public class Dummies {
private static class NoMethodShouldBeCalledAnswer implements Answer<Object> {
private String className;
public NoMethodShouldBeCalledAnswer(String className) {
this.className = className;
}
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
throw new RuntimeException("This " + className + " is a dummy test double. None of its methods should be called.\n" +
"Method called: " + invocation.getMethod());
}
}
public static <D> D createDummy(Class<D> classToDummy) {
return mock(classToDummy, new NoMethodShouldBeCalledAnswer(classToDummy.getSimpleName()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment