How to simulate javax servlet. ServletInputStream
•
Java
I'm creating some unit tests and trying to simulate some calls This 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:
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,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 want to do is request Getinputstream(), the stream returns some strings
HttpServletRequest request = mock(HttpServletRequest.class); ServletInputStream inputStream = mock(ServletInputStream.class); when(request.getInputStream()).thenReturn(inputStream);
So that's what I want
when(inputStream.read()).thenReturn("My String".toInt());
Any help would be appreciated
Solution
Do not simulate InputStream Instead, use Convert string to byte array
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(); } }
Finally, HttpServletRequest mock will return this delegatingservletinputstream object
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码