Search code examples
javaunit-testingserializationapache-kafkaavro

Avro - Unable to serialize payload org.apache.avro.AvroRuntimeException: Unknown datum type java.math.BigDecimal: 8.32


I'm writing unit test to one of the method which is sending event to kafka.

In avro schema I have defined filed

union { decimal(10, 2), null } cost

which is represented in Java as BigDecimal.

In the unit test I'm using DatumReader for reading if event was correctly sent to topic.

    private final DatumReader<Event> eventReader = new SpecificDatumReader<>(Event.class);

    //reading message from topic
    final ConsumerRecord<String, byte[]> eventMessage = KafkaTestUtils.getSingleRecord(
        kafkaConsumer, eventTopic, ofSeconds(10).toMillis()
    );
    final Event event = eventReader.read(
        null,
        DecoderFactory.get().binaryDecoder(eventMessage.value(), null)
    );

And finally I'm receiving an error

Unable to serialize payload org.apache.avro.AvroRuntimeException: Unknown datum type java.math.BigDecimal: 8.32

Is anyone know how to fix it?


Solution

  • Finally adding

    GenericData.get().addLogicalTypeConversion(new Conversions.DecimalConversion());
    

    before calling read() method

    final Event event = eventReader.read(
        null,
        DecoderFactory.get().binaryDecoder(eventMessage.value(), null)
    );
    

    fixed the problem.