ghost
ghost

Reputation: 1207

Mocking a Kafka consumer in Scala

I'm trying to mock a Kafka Consumer in Scala. However, I'm getting a NullPointerException.

The following is my mocking code:

val kafkaConsumerMock: KafkaConsumer[String, Any] = mock[KafkaConsumer[String, Any]]

The error I'm getting is:

java.lang.NullPointerException
    at java.util.HashMap.putMapEntries(HashMap.java:501)
    at java.util.HashMap.<init>(HashMap.java:490)
    at org.apache.kafka.clients.consumer.ConsumerConfig.addDeserializerToConfig(ConsumerConfig.java:523)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:629)
    at org.apache.kafka.clients.consumer.KafkaConsumer.<init>(KafkaConsumer.java:610)

When I'm trying to debug, I see that there are multiple constructors, each calling a private constructor at the end. Thereafter the private constructor performs some checks, and throws an NPE as the configs I'm passing to KafkaConsumer are null (but mocking shouldn't require parameters to be passed, right?).

What I'm unable to understand is, why is the actual code being called when I'm trying to mock? Also, how do I get around this?

Edit: I'm using MockFactory

Attached herewith is the debug status. mock returns a null consumer.

This is the debug point status

Upvotes: 1

Views: 1088

Answers (2)

OneCricketeer
OneCricketeer

Reputation: 191681

You can initialize a MockConsumer rather than using external mocking library.

Or if you want to inject mocks into another class, your external class would need to use the org.apache.kafka.clients.consumer.Consumer interface rather than KafkaConsumer implementation.

Upvotes: 4

Boris Azanov
Boris Azanov

Reputation: 4481

your problem is trying to mock some class that is not Abstract. You can mock some traits or Java interfaces or abstract classes but not regular classes. So, as @OneCricketeer advised, you can use MockConsumer which should be assigned to a value of Consumer[String, Any] type:

import org.apache.kafka.clients.consumer.{Consumer, MockConsumer, OffsetResetStrategy}
val kafkaConsumerMock: Consumer[String, Any] = new MockConsumer[String, Any](OffsetResetStrategy.LATEST)

or mock Consumer[String, Any]

val kafkaConsumerMock: Consumer[String, Any] = mock[Consumer[String, Any]]

Upvotes: 1

Related Questions