我很新Mockito和嘲笑servlets進行測試。我有問題嘲笑一個HttpServletRequest,它將一些表單數據作爲MimeMultiPart發送到我的servlet。在我的servlet我打電話request.getInputStream()
如下:mockito嘲笑mockito的多部分mime請求
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不可序列化,但我不知道如何解決這個問題。是否有另一種方法來模擬請求?我很茫然:(
你打算如何在測試使用'MimeMultipart'對象後也許你應該在更高層次上嘲笑(即模擬一個組件,它根據請求獲取'MimeMultiPart') – ShyJ
解析出消息並進行驗證,我認爲這不是一種測試servlet行爲的好方法,但它不是我的調用,我只是一個猴子\\ _(oO)_/ –