簡體   English   中英

如何模擬javax.servlet.ServletInputStream

[英]How to Mock a javax.servlet.ServletInputStream

我正在創建一些單元測試並嘗試模擬一些調用。 這是我在工作代碼中的內容:

String soapRequest = (SimUtil.readInputStream(request.getInputStream())).toString();
if (soapRequest.equals("My String")) { ... }

和SimUtil.readInputSteam看起來像這樣:

StringBuffer sb = new StringBuffer();
BufferedReader reader = null;
try  {
    reader = new BufferedReader(new InputStreamReader(inputStream));
    final int buffSize = 1024;
    char[] buf = new char[buffSize];
    int numRead = 0;
    while ((numRead = reader.read(buf)) != -1) {
        String readData = String.valueOf(buf, 0, numRead);
        sb.append(readData);
        buf = new char[buffSize];
    }
} catch (IOException e) {
    LOG.error(e.getMessage(), e);
} finally {
    try {
        if (reader != null) {
            reader.close();
        }
    } catch (IOException e) {
        LOG.error(e.getMessage(), e);
    }
}

我想要做的是request.getInputStream(),流返回某些String。

HttpServletRequest request = mock(HttpServletRequest.class);
ServletInputStream inputStream = mock(ServletInputStream.class);
when(request.getInputStream()).thenReturn(inputStream);

所以這是我想要的條件

when(inputStream.read()).thenReturn("My String".toInt());

任何幫助將不勝感激。

不要模擬InputStream。 而是使用getBytes()方法將String轉換為字節數組。 然后使用數組作為輸入創建一個ByteArrayInputStream,以便在消耗時返回String,每次返回每個字節。 接下來,創建一個ServletInputStream,它包裝一個常規的InputStream,就像Spring中的那樣:

public class DelegatingServletInputStream extends ServletInputStream {

    private final InputStream sourceStream;


    /**
     * Create a DelegatingServletInputStream for the given source stream.
     * @param sourceStream the source stream (never <code>null</code>)
     */
    public DelegatingServletInputStream(InputStream sourceStream) {
        Assert.notNull(sourceStream, "Source InputStream must not be null");
        this.sourceStream = sourceStream;
    }

    /**
     * Return the underlying source stream (never <code>null</code>).
     */
    public final InputStream getSourceStream() {
        return this.sourceStream;
    }


    public int read() throws IOException {
        return this.sourceStream.read();
    }

    public void close() throws IOException {
        super.close();
        this.sourceStream.close();
    }

}

最后,HttpServletRequest mock將返回此DelegatingServletInputStream對象。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM