简体   繁体   中英

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.

这是调试点状态

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.

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]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM