Mockito: Mock a JspWriter

How to Mock a JspWriter to move the appended text to a StringBuilder?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
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());

Here we are :-)