Mockito:模拟InputStream的异常#read(byte [])

时间:2014-06-17 13:42:46

标签: java mockito

我想让InputStream返回我想要的值。所以我这样做:

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

private Byte[] getNextPortionOfData() { ...

例外: java.lang.Byte; cannot be cast to java.lang.Number

问题:为什么?!为什么我得到那个例外?

1 个答案:

答案 0 :(得分:2)

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

所以你需要这样的东西:

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;            
    }
});

但是,我可能不会使用模拟器 - 如果绝对必要,我会使用假的,否则使用ByteArrayInputStream。我只使用真正细粒度控件的模拟,例如“如果我的输入编码文本流在一次调用中返回字符的前半部分会发生什么,然后在下一个调用中的余数......“