I would like to simulate a behaviour in a unit test of an InputStream that (as InputStreams do) blocks until further data is available. That requires me to append bytes to the InputStream in chunks so that the consumer reads them in chunks, too. Something like this:
@Test
public void readAllInput() throws Exception {
???InputStream in = ...; // ???
Consumer consumer = new Consumer(in);
Thread consumingThread = new Thread(consumer).start();
in.add("one".getBytes("UTF-8")); // ???
in.add("two".getBytes("UTF-8")); // ???
in.close();
consumingThread.join();
assertThat(consumer.getDataAsString()).isEqualTo("onetwo");
}
class Consumer implements Runnable {
private InputStream in;
private ByteArrayOutputStream out = new ByteArrayOutputStream();
public Consumer(InputStream in) {
this.in = in;
}
public void run() {
IOUtils.copy(in, out);
}
public String getDataAsString() {
return out.toString("UTF-8");
}
}
What kind of InputStream (or any other solution) would allow me to append the data on one end and consume them from the other?
Note: The Consumer needs to have InputStream-based API (not Reader).
As you're using threads, this is a rare case for a pair of PipedInputStream/PipedOutputStream.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With