Java Mockito:mock InputStream#read(字节[])异常

Java Mockito:mock InputStream#read(字节[])异常,java,mockito,Java,Mockito,我想要获取InputStream并返回我想要的值。因此,我: doAnswer(new Answer<Byte[]>() { @Override public Byte[] answer(InvocationOnMock invocationOnMock) throws Throwable { return getNextPortionOfData(); } }).when(inputMock).read(any(byte[].class));

我想要获取InputStream并返回我想要的值。因此,我:

doAnswer(new Answer<Byte[]>() {
    @Override
    public Byte[] answer(InvocationOnMock invocationOnMock) throws Throwable {
        return getNextPortionOfData();
    }
}).when(inputMock).read(any(byte[].class));

private Byte[] getNextPortionOfData() { ...
doAnswer(新答案(){
@凌驾
公共字节[]应答(InvocationMock InvocationMock)抛出可丢弃的{
返回getNextPortionOfData();
}
}).when(inputMock).read(any(byte[].class));
私有字节[]getNextPortionOfData(){。。。
异常:
java.lang.Byte;无法转换为java.lang.Number


问题:为什么?!我为什么会出现这种异常?

您试图从调用中返回
字节[]
,但是
InputStream.read(字节[])
返回读取的字节数,并将数据存储在参数引用的字节数组中

所以你需要像这样的东西:

doAnswer(new Answer<Integer>() {
    @Override
    public Integer answer(InvocationOnMock invocationOnMock) throws Throwable {
        Byte[] bytes = getNextPortionOfData();
        // TODO: Copy the bytes into the argument byte array... and
        // check there's enough space!
        return bytes.length;            
    }
});
doAnswer(新答案(){
@凌驾
公共整数应答(invocationMock invocationMock)抛出可丢弃的{
Byte[]bytes=getNextPortionOfData();
//TODO:将字节复制到参数字节数组中…和
//检查是否有足够的空间!
返回bytes.length;
}
});
然而,无论如何,我可能不会为此使用模拟-如果绝对必要,我会使用模拟,否则我会使用
ByteArrayInputStream
。我只会使用模拟进行真正细粒度的控制,例如“如果我的编码文本输入流在一次调用中返回前半个字符,然后在下一次调用中返回其余字符,会发生什么情况…”