Reputation: 3365
I'm pretty new to Mockito and mocking out servlets for testing. I'm having problems mocking out an HttpServletRequest which sends some form data to my servlet as a MimeMultiPart. In my servlet I call request.getInputStream()
as follows:
mimeMultiPart = new MimeMultipart(new ByteArrayDataSource(
request.getInputStream(), Constants.MULTI_PART_FORM_DATA));
When I mock out my input stream I create an entire MimeMultiPart message and then I try to return a ServletInputStream from it in the code below
//Helper function to create ServletInputStream
private ServletInputStream createServletInputStream(Object object)
throws Exception {
//create output stream
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
ObjectOutputStream outStream = new ObjectOutputStream(byteOut);
//this part no workey
outStream.writeObject(object);
//create input stream
final InputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
//create a new ServletInputStream and return it
return new ServletInputStream() {
@Override
public int read() throws IOException {
return byteIn.read();
}
};
}
@Test
public void testDoPost() throws Exception {
PrintWriter writer;
writer = new PrintWriter("testSendMultiPartBatchResponse.txt");
when(response.getWriter()).thenReturn(writer);
//this is the mocked request
when(request.getInputStream()).thenReturn(
createServletInputStream(multiPartResponse));
. . .
now when I run this test I receive the following error on outStream.writeObject(object)
:
java.io.NotSerializableException: javax.mail.internet.MimeMultipart
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)
. . .
it's not necessary to post the rest of the stack trace, I'm pretty sure the problem is that MimeMultiPart is not serializable, but I don't know how to rectify this. Is there another way to mock out the request? I am at a loss :(
Upvotes: 4
Views: 4903
Reputation: 4640
I think this should work:
final ByteArrayOutputStream os = new ByteArrayOutputStream ();
multiPartResponse.writeTo (os);
final ByteArrayInputStream is = new ByteArrayInputStream (os.toByteArray ());
when(request.getInputStream()).thenReturn(new ServletInputStream() {
@Override
public int read() throws IOException {
return is.read();
}
});
Upvotes: 7