Skip to content

Instantly share code, notes, and snippets.

@kntmr
Last active Dec 20, 2016
Embed
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.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Test;
public class InputStreamTest {
@Test
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;
@Override
protected boolean matchesSafely(InputStream actual) {
try {
left = read(actual);
right = read(expected);
return Arrays.equals(left, right);
} catch (IOException e) {
}
return false;
}
@Override
public void describeTo(Description description) {
description.appendValue(new String(right));
}
@Override
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 = input.read(buff);
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