简体   繁体   English

间谍 InputStream.read(byte[] buffer)

[英]Spy InputStream.read(byte[] buffer)

I'm trying to create a test where the third request will throw an error and validate the input of the previous ones.我正在尝试创建一个测试,其中第三个请求将抛出错误并验证前一个请求的输入。

@Test
void sample() throws IOException {
    var is = spy(new ByteArrayInputStream(new byte[]{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
    doReturn(3, 3, 3)
            .doThrow(new IOException("FOO"))
            .when(is)
            .read(any());
    byte[] buf = new byte[3];
    assertThat(is.read(buf)).isEqualTo(3);
    assertThat(buf).isEqualTo(new byte[]{0,1,2});
}

What I got was我得到的是

expected: [0, 1, 2]
 but was: [0, 0, 0]

Is this a limitation of Mockito spy or is there something I am missing.这是 Mockito spy的限制还是我遗漏了什么。

Since I want the normal behaviour, there's actually a doCallRealMethod() Stubber that can be used instead of having to return the value which will update the buffer as expected.因为我想要正常的行为,所以实际上有一个doCallRealMethod() Stubber可以使用,而不必返回将按预期更新缓冲区的值。

  @Test
  void validateSpyByteInputStream() throws IOException {
    var is = spy(new ByteArrayInputStream(new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}));
    doCallRealMethod()
        .doCallRealMethod()
        .doCallRealMethod()
        .doThrow(new IOException("FOO"))
        .when(is)
        .read(any(byte[].class));
    byte[] buf = new byte[3];
    assertThat(is.read(buf)).isEqualTo(3);
    assertThat(buf).isEqualTo(new byte[] {0, 1, 2});
    assertThat(is.read(buf)).isEqualTo(3);
    assertThat(buf).isEqualTo(new byte[] {3, 4, 5});
    assertThat(is.read(buf)).isEqualTo(3);
    assertThat(buf).isEqualTo(new byte[] {6, 7, 8});
    assertThatThrownBy(() -> is.read(buf)).isInstanceOf(IOException.class).hasMessage("FOO");
  }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM