7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ServletInputStreamモック化

Posted at

JUnitなどでServletのテストを行う時にServletRequestをモック化します。
その際にServletInputStreamから読み出す文字列を、呼び出し側で指定できるようにフックしたものです。

TestUtil.java
public static ServletInputStream createServletInputStream(String s, String charset) {
	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	try {
		baos.write(s.getBytes(charset));
	} catch (Exception e) {
		throw new RuntimeException("No support charset.");
	}

	final InputStream bais = new ByteArrayInputStream(baos.toByteArray());

	return new ServletInputStream() {

		@Override
		public int read() throws IOException {
			return bais.read();
		}
	};
}

Mockitoを使ってモック化する場合、下記のように使用します。

HogeTest.java
String xml = "....";
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
when(request.getInputStream()).thenReturn(TestUtil.createServletInputStream(xml, "UTF-8"));
target.doPost(request, response);
7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?