我正在创建一些单元测试并尝试模拟一些调用。这是我的工作代码中的内容:
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/