Skip to content

Instantly share code, notes, and snippets.

Last active Dec 20, 2016
What would you like to do?
InputStream のカスタム Matcher
package sample;
import static sample.InputStreamTest.InputStreamMatchers.*;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.Arrays;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
public class InputStreamTest {
public void test() throws Exception {
InputStream expected = new ByteArrayInputStream("hoge".getBytes());
InputStream actual = new ByteArrayInputStream("hoge".getBytes());
assertThat(actual, is(equalTo(expected)));
public static class InputStreamMatchers {
public static Matcher<InputStream> equalTo(final InputStream expected) {
return new TypeSafeMatcher<InputStream>() {
private byte[] left, right;
protected boolean matchesSafely(InputStream actual) {
try {
left = read(actual);
right = read(expected);
return Arrays.equals(left, right);
} catch (IOException e) {
return false;
public void describeTo(Description description) {
description.appendValue(new String(right));
protected void describeMismatchSafely(InputStream actual, Description mismatchDescription) {
mismatchDescription.appendValue(new String(left));
private static byte[] read(InputStream input) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
byte[] buff = new byte[1024];
while (true) {
int length =;
if (length < 0) break;
out.write(buff, 0, length);
return out.toByteArray();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment