Assert an InputStream and an Output stream are equal

7.1k Views Asked by At

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?

2

There are 2 best solutions below

0
On

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.

0
On

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.