2012-11-12 42 views
2

我很新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不可序列化,但我不知道如何解決這個問題。是否有另一種方法來模擬請求?我很茫然:(

+0

你打算如何在測試使用'MimeMultipart'對象後也許你應該在更高層次上嘲笑(即模擬一個組件,它根據請求獲取'MimeMultiPart') – ShyJ

+0

解析出消息並進行驗證,我認爲這不是一種測試servlet行爲的好方法,但它不是我的調用,我只是一個猴子\\ _(oO)_/ –

回答

5

我認爲這應該工作:

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

謝謝!這讓我在駝峯......像往常一樣,我把事情做得比他們的要艱難,因爲request.getInputStream()需要一個ServletInputStream而不是ByteArrayInputStream ...我編輯了你r答案以反映我的變化。再次感謝! –

+0

@本Glasser,我仍然認爲這是一個好主意,把它變成一個靜態方法,接受一個對象,並返回流......當你的問題顯示你在做什麼。 –