Mockito | JUnit | Avro:模拟void方法不起作用

问题描述

我写了一个要测试的avro序列化方法。

方法

@SneakyThrows
@Override
public byte[] serialize(String topic,T data) {
    try (ByteArrayOutputStream stream = new ByteArrayOutputStream()) {
        writeSerializedAvro(stream,data,data.getSchema());
        return stream.toByteArray();
    } catch (IOException e) {
        throw new AvroSerializationException(e.getMessage(),e);
    }
}

private void writeSerializedAvro(ByteArrayOutputStream stream,T data,Schema schema) throws IOException {
    binaryEncoder = EncoderFactory.get().binaryEncoder(stream,binaryEncoder);
    DatumWriter<T> datumWriter = new GenericDatumWriter<>(schema);
    datumWriter.write(data,binaryEncoder);
    binaryEncoder.flush();
}

datumWriter.writebinaryEncoder.flush()可以抛出IOException

在测试中,我想查看是否抛出了IOException,我的方法捕获了它并将其包装在AvroSerializationException(我写的一个类)中。

单元测试

    @Test(expected = AvroSerializationException.class)
public void testSerializeException() throws IOException {
    // Given 
// need to mock here

    // When
    serializer.serialize("",avroObject);
}

我尝试使用GenericDatumWriter方法对BufferedBinaryEncoderEncoderFactorydoThrow().when()进行模拟,但没有任何效果。

BufferedBinaryEncoder binaryEncoder = Mockito.mock(BufferedBinaryEncoder.class);
Mockito.doThrow(new IOException()).when(binaryEncoder).flush();

    GenericDatumWriter datumWriter = Mockito.mock(GenericDatumWriter.class);
    Mockito.doThrow(new IOException()).when(datumWriter).write(any(),any());

但是,问题又回到了我应该如何将这些对象传递给序列化器,同时牢记最佳实践?

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)