我正在创建一些单元测试并尝试模拟一些调用。这是我的工作代码中的内容:
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());
任何帮助将不胜感激。
不要嘲笑输入流。相反,使用 getBytes() 方法。然后创建一个 ByteArrayInputStream,将数组作为输入,以便在使用时返回字符串,一次返回每个字节。接下来,创建一个 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 模拟将返回这个 DelegatingServletInputStream 对象。