Created
January 23, 2016 23:36
-
-
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)
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
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