Advertisement
Guest User

Fluent interface in Mockito

a guest
Mar 16th, 2014
259
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.07 KB | None | 0 0
  1. import org.mockito.internal.stubbing.defaultanswers.ReturnsEmptyValues;
  2. import org.mockito.invocation.InvocationOnMock;
  3. import org.mockito.stubbing.Answer;
  4.  
  5. /**
  6.  * Class for testing fluent interfaces. Based mostly on this blog post:
  7.  *
  8.  * http://jakegoulding.com/blog/2012/01/09/stubbing-builder-pattern-in-mockito/
  9.  *
  10.  * @author durron597
  11.  */
  12. public class AnswerWithSelf implements Answer<Object> {
  13.     private final Answer<Object> delegate;
  14.     private final Class<?> clazz;
  15.  
  16.     public AnswerWithSelf(Class<?> clazz) {
  17.         this.clazz = clazz;
  18.         this.delegate = new ReturnsEmptyValues();
  19.     }
  20.  
  21.     public AnswerWithSelf(Class<?> clazz, Answer<Object> delegate) {
  22.         this.clazz = clazz;
  23.         this.delegate = delegate;
  24.     }
  25.    
  26.     public Object answer(InvocationOnMock invocation) throws Throwable {
  27.         Class<?> returnType = invocation.getMethod().getReturnType();
  28.         if (returnType.isAssignableFrom(clazz)) {
  29.             return invocation.getMock();
  30.         } else {
  31.             return delegate.answer(invocation);
  32.         }
  33.     }
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement