'Writing JUnit tests for Kafka Consumer

I have a kafka consumer which is subscribing on a topic. Implementation is working fine. But when trying to implement unit tests for that, there's a problem because of it's implementing by Runnable interface.

Implementation

@Override
public void run() {
    kafkaConsumer.subscribe(kafkaTopics);

    while (true) {
        ConsumerRecords<String, String> records = kafkaConsumer.poll(1000);
        Map<String, InventoryStock> skuMap = new LinkedHashMap<>();

        try {
            // populating sku map with consumer record
            for (ConsumerRecord<String, String> record : records) {
                populateMap(skuMap, record.value());
            }

            if (MapUtils.isNotEmpty(skuMap)) {
                // writing sku inventory with populated sku map
                inventoryDao.updateInventoryTable(INVENTORY_JOB_ID, skuMap);
            }
        } catch (Exception e) {

        }
        kafkaConsumer.commitAsync();
    }
}

I tried to implement the tests using MockConsumer. But it needs to be assigned to the consumer in implementation. But consumer in implementation doesn't expose out side. Here what I tried.

@Before
public void onBefore() {
    MockitoAnnotations.initMocks(this);

    Properties consumerProps = new Properties();
    consumerProps.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    consumerProps.put(ConsumerConfig.GROUP_ID_CONFIG, "test-group");
    consumerProps.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
    consumerProps.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);

    consumer = new MockConsumer<>(OffsetResetStrategy.EARLIEST);
    skuInventoryConsumer = new SkuInventoryConsumer(consumerProps);

    KafkaConsumer kafkaConsumerMock = mock(KafkaConsumer.class);

    Whitebox.setInternalState(skuInventoryConsumer, "LOGGER", LOGGER);
    Whitebox.setInternalState(skuInventoryConsumer, "kafkaConsumer", kafkaConsumerMock);

}

@Test
public void should_subscribe_on_topic() {
    consumer.assign(Arrays.asList(new TopicPartition("my_topic", 0)));

    HashMap<TopicPartition, Long> beginningOffsets = new HashMap<>();
    beginningOffsets.put(new TopicPartition("my_topic", 0), 0L);
    consumer.updateBeginningOffsets(beginningOffsets);

    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 0L, "mykey", "myvalue0"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 1L, "mykey", "myvalue1"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 2L, "mykey", "myvalue2"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 3L, "mykey", "myvalue3"));
    consumer.addRecord(new ConsumerRecord<>("my_topic", 0, 4L, "mykey", "myvalue4"));
}

Since it's a runnable and consumer is not exposed this test not working as expected. How may I fix this?



Solution 1:[1]

I would suggest to use Mockito, like below sample

Consumer<String, String> kafkaConsumerLocal = mock(Consumer.class);
KafkaConsumer kafkaConsumer = spy(new KafkaConsumer("topic-name"));

ReflectionTestUtils.setField(kafkaConsumer, "threadPoolCount", 1);
ReflectionTestUtils.setField(kafkaConsumer, "consumer", kafkaConsumerLocal);

doNothing().when(kafkaConsumer).runConsumer();
doNothing().when(kafkaConsumer).addShutDownHook();
doReturn(kafkaConsumerLocal).when(consumerInit).getKafkaConsumer();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Didier L