Is there any simple way to test (in Junit) if the content of an input stream is equal to the content of an output one?
Assert an InputStream and an Output stream are equal
7.1k Views Asked by user3727540 At
2
There are 2 best solutions below
0

There is no built in way, but you might still be able to test it. It depends what you are doing. Here is a simple case...
Say if I had this method...
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.springframework.util.StreamUtils;
public class Stack {
public static void copy(InputStream in, OutputStream out) {
try {
StreamUtils.copy(in, out);
} catch(IOException io) {
throw new RuntimeException("BOOM!");
}
}
}
I could test this method like this...
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Arrays;
import org.junit.Test;
public class StackTest {
@Test
public void shouldCopyFromInputToOutput() {
byte[] contents = new byte[] { 1, 2, 3 };
ByteArrayOutputStream out = new ByteArrayOutputStream();
Stack.copy(new ByteArrayInputStream(contents), out);
byte[] written = out.toByteArray();
assert Arrays.equals(contents, written);
}
}
So I am not testing if the output and input streams are "equal", but instead I am making assertions on what the method actually does.
Hope this helps.
Not only there is no simple way to test this, there is no way to make this comparison in general case.
You need to make your own wrapper around the output stream, pass it to the program being tested, and then harvest what has been written into it. After that you can read your input stream, and compare its content with what has been captured.
ByteArrayOutputStream
may help you capture the output of the code that you test. Commons IO provide two classes that may be helpful -TeeInputStream
andTeeOutputStream
.