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?
-
2I'm missing some context here. Can you share the code (or at least the signature) of the method you're trying to test? – Mureinik Dec 31 '16 at 12:19
-
Are you going to write *UnitTest*s (in contrast to writing *acceptance/rejection test*s using JUnitFramework)? If the first you should replace the Input-/OutputStream by Mocks (using Mokito or alike) then you can check that what you configured the IS to return is transfered to the OS... – Timothy Truckle Dec 31 '16 at 12:28
-
Let me explain what I am doing here: I got a function that sorts data coming from an inputstream (XML data) and writes the result on the provided output stream. I would like to test if the resulting outputstream content (written in a file) is equal to an expected file content. – user3727540 Dec 31 '16 at 12:35
2 Answers
Not only there is no simple way to test this, there is no way to make this comparison in general case.
- An output stream is an abstraction that allows write-only implementations for transmit-and-forget streams. There is no general way to get back what has been written
- An input stream may not allow rewinding. This is less of a problem, because you may be OK with "destructive" reads, but one needs to be careful in that area as well.
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
and TeeOutputStream
.

- 714,442
- 84
- 1,110
- 1,523
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.

- 4,141
- 13
- 22