java - 如何模拟 javax.servlet.ServletInputStream

标签 java unit-testing servlets inputstream mockito

我正在创建一些单元测试并尝试模拟一些调用。这是我的工作代码中的内容:

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(),流返回特定的字符串。

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

所以这是我要调整的代码

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

任何帮助将不胜感激。

最佳答案

不要模拟 InputStream。相反,使用 getBytes() 方法。然后使用数组作为输入创建一个 ByteArrayInputStream,以便它在使用时返回 String,一次每个字节。接下来,创建一个 ServletInputStream,它包装一个常规的 InputStream,就像来自 Spring 的 InputStream 一样:

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 模拟将返回此 DelegatingServletInputStream 对象。

关于java - 如何模拟 javax.servlet.ServletInputStream,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20995874/

相关文章:

java - struts2 和 jaxb(适用于高于 2.0.x 的 struts2 版本)

java - 如何在eclipse中创建一个文件夹来存储序列化对象?

java - 减少代码的执行时间

unit-testing - VS2012/2013 是在构建后自动运行每个测试,还是只运行那些接触受影响代码的测试?

javascript - 预期等于结果时出现不可变的 Chai 断言错误

java - 使用 ServletContext 的 session 对象

java - 告诉 java 要听哪个键盘

java - 如何使用私有(private)方法调用 Mockito.given

java - 检查应用程序是否在 Android 电子市场上可用

jsp - 如何验证授权的表单提交