Skip to content

Instantly share code, notes, and snippets.

@idefixcert
Last active December 16, 2015 18:19
Show Gist options
  • Select an option

  • Save idefixcert/5476754 to your computer and use it in GitHub Desktop.

Select an option

Save idefixcert/5476754 to your computer and use it in GitHub Desktop.
Mockito: Mock a JspWriter
StringBuilder buffer = new StringBuilder();
JspWriter jspWriterMock = mock(JspWriter.class);
Answer<JspWriter> answer = new Answer<JspWriter>() {
@Override
public JspWriter answer(final InvocationOnMock theInvocation) throws Throwable {
Method method = theInvocation.getMethod();
Method methodImpl = StringBuilder.class.getMethod(method.getName(), method.getParameterTypes());
methodImpl.invoke(buffer, theInvocation.getArguments());
return (JspWriter) theInvocation.getMock();
}
};
Answer<Void> answerB = new Answer<Void>() {
@Override
public Void answer(final InvocationOnMock theInvocation) throws Throwable {
buffer.append(theInvocation.getArguments()[0]);
return null;
}
};
when(jspWriterMock.append(Matchers.anyChar())).thenAnswer(answer);
when(jspWriterMock.append(Matchers.anyString())).thenAnswer(answer);
when(jspWriterMock.append(Matchers.anyString(),Matchers.anyInt(),Matchers.anyInt())).thenAnswer(answer);
doAnswer(answerB).when(jspWriterMock).write(Matchers.anyString());
doAnswer(answerB).when(jspWriterMock).write((char[])Matchers.anyVararg());
doAnswer(answerB).when(jspWriterMock).write(Matchers.anyInt());
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment