Mock a sequence of calls to different methods

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
java
mocking
mockito
asked on Stack Overflow Dec 16, 2019 by Jörg Weichelt • edited Dec 16, 2019 by Jörg Weichelt

0 Answers

Nobody has answered this question yet.


User contributions licensed under CC BY-SA 3.0