0

I want to unit test a class that reads data from a stream in a certain protocol. This will require different read() Methods on the stream in a certain order. Is there a way to mock the stream like this:

MyClass readFrom(InputStream in) {
  byte b = in.readByte();
  int c = in.readInt();
  byte b2 = in.readByte();
  return MyClass(b, c, b2);
}

MyInputStream in = Mockito.mock(MyInputStream.class);
when(in.readByte()).thenReturn(0x01);  // 0
when(in.readInt()).theReturn(0xDEADBEEF);  // 1
when(in.readByte()).thenReturn(0x00);  // 2

The only - ugly - way I found out is this:

MyInputStream in = Mockito.mock(MyInputStream.class);
when(in.readByte())
  .thenReturn(0x01) // 0
  .thenReturn(0x00); // 2
when(in.readInt()).thenReturn(0xDEADBEEF); // 1
  • Does this answer your question? [Mocking Java InputStream](https://stackoverflow.com/questions/6371379/mocking-java-inputstream) – second Dec 16 '19 at 21:20
  • Instead of mocking it, setup a real InputStream, like suggest in this [answer](https://stackoverflow.com/a/6371511). – second Dec 16 '19 at 21:21
  • Unfortunately, `MyInputStream`does some decoding. So if I provide a real InputStream, I need to fill it with encoded data, what makes the test less clear and will be a test for the decoding functions rather than for stream reading. – Jörg Weichelt Dec 17 '19 at 06:22
  • Maybe using a spy on your InputStream and only defining behaviour for something like `readFully` (assuming all your read methods share a common read method, that handles the decoding before it transform the result into the datatype you want) might be an option for you? – second Dec 17 '19 at 13:01

0 Answers0