![](/img/trans.png)
[英]Mocking a void method in the same class that is under test with mockito and junit5?
[英]Mockito | JUnit | Avro: Mocking a void method does not work
我寫了一個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.write
或binaryEncoder.flush()
可以拋出IOException
。
在測試中,我想看看是否IOException
,我的方法捕獲它並將其包裝在AvroSerializationException
(我編寫的一個類)中。
單元測試
@Test(expected = AvroSerializationException.class)
public void testSerializeException() throws IOException {
// Given
// need to mock here
// When
serializer.serialize("", avroObject);
}
我曾嘗試使用doThrow().when()
方法doThrow().when()
GenericDatumWriter
、 BufferedBinaryEncoder
和EncoderFactory
,但沒有任何效果對我doThrow().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());
但是,問題又回到了,我應該如何將這些對象傳遞給我的序列化程序,同時牢記最佳實踐?
您需要首先使用 Mockito 模擬對象並在您的類中使用它,然后將拋出異常,如下所示:
您的代碼:
private DatumWriter<T> datumWriter = new GenericDatumWriter<>(schema);
@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.write(data, binaryEncoder);
binaryEncoder.flush();
}
public void setDatumWriter (DatumWriter datumWriter){
this.datumWriter=datumWriter;
}
您的測試代碼:
@Test(expected = AvroSerializationException.class)
public void testSerializeException() throws IOException {
// Given
DatumWriter<YourClass> datumWriter = Mockito.mock(DatumWriter<YourClass>.class);
when(datumWriter.write(anyObject(), anyObject())).thenThrow(IOException.class);
serializer.setDatumWriter(datumWriter);
serializer.serialize("", avroObject);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.