Last active
December 20, 2016 07:59
-
-
Save kntmr/3e9796730562923bfd6db3527f1ab766 to your computer and use it in GitHub Desktop.
InputStream のカスタム Matcher
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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