我对Mockito相当陌生,可以模拟servlet进行测试。我在模拟HttpServletRequest时遇到问题,该HttpServletRequest将一些表单数据作为MimeMultiPart发送到我的servlet。在我的servlet中,我按以下方式调用request.getInputStream():

mimeMultiPart = new MimeMultipart(new ByteArrayDataSource(
                request.getInputStream(), Constants.MULTI_PART_FORM_DATA));

当我模拟输入流时,我会创建一条完整的MimeMultiPart消息,然后尝试在下面的代码中从中返回一个ServletInputStream
    //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));

. . .

现在,当我运行此测试时,我在outStream.writeObject(object)上收到以下错误:
java.io.NotSerializableException: javax.mail.internet.MimeMultipart
at java.io.ObjectOutputStream.writeObject0(Unknown Source)
at java.io.ObjectOutputStream.writeObject(Unknown Source)

    . . .

不必发布其余的堆栈跟踪,我很确定问题是MimeMultiPart无法序列化,但是我不知道如何解决。还有另一种模拟请求的方法吗?我很茫然 :(

最佳答案

我认为这应该工作:

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();
        }
    });

10-06 09:46