4

我对 Mockito 和模拟 servlet 进行测试还很陌生。我在模拟 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 不可序列化,但我不知道如何纠正这个问题。还有另一种方法来模拟请求吗?我很茫然 :(

4

1 回答 1

7

我认为这应该有效:

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();
        }
    });
于 2012-11-13T00:08:07.383 回答