[英]How to Mock a javax.servlet.ServletInputStream
I am creating some unit testing and trying to Mock out some calls. 我正在创建一些单元测试并尝试模拟一些调用。 Here is what I have in my working code:
这是我在工作代码中的内容:
String soapRequest = (SimUtil.readInputStream(request.getInputStream())).toString();
if (soapRequest.equals("My String")) { ... }
and SimUtil.readInputSteam looks like this: 和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);
}
}
What I am trying to do is the request.getInputStream(), the stream returns certain String. 我想要做的是request.getInputStream(),流返回某些String。
HttpServletRequest request = mock(HttpServletRequest.class);
ServletInputStream inputStream = mock(ServletInputStream.class);
when(request.getInputStream()).thenReturn(inputStream);
So This is the code I want to condition 所以这是我想要的条件
when(inputStream.read()).thenReturn("My String".toInt());
Any Help would be greatly appreciated. 任何帮助将不胜感激。
Don't mock the InputStream. 不要模拟InputStream。 Instead, transform the String to an array of bytes using the getBytes() method.
而是使用getBytes()方法将String转换为字节数组。 Then create a ByteArrayInputStream with the array as input, so that it returns the String when consumed, each byte at a time.
然后使用数组作为输入创建一个ByteArrayInputStream,以便在消耗时返回String,每次返回每个字节。 Next, create a ServletInputStream that wraps a regular InputStream like the one from Spring:
接下来,创建一个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();
}
}
and finally, the HttpServletRequest mock would return this DelegatingServletInputStream object. 最后,HttpServletRequest mock将返回此DelegatingServletInputStream对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.