我试图嘲笑org.apache.kafka.clients.producer.KafkaProducer
.但是模拟失败了,因为类的实现。验证输入参数,如果为 null,则引发空指针异常。我怎么能模拟它?
我认为它失败的原因是,类KafkaProducer
的第一个参数是一个扩展AbstractConfig
的ProducerConfig
。它验证传递的属性。如果为 null,则引发 null 指针异常。
import org.apache.kafka.clients.producer.{KafkaProducer, ProducerConfig}
import org.scalamock.scalatest.MockFactory
object MyProducerTest extends MockFactory with App {
val mockKafkaProducer = mock[KafkaProducer[String,String]]
}
Exception in thread "main" java.lang.NullPointerException
at org.apache.kafka.common.config.AbstractConfig.<init>(AbstractConfig.java:52)
at org.apache.kafka.common.config.AbstractConfig.<init>(AbstractConfig.java:63)
at org.apache.kafka.clients.producer.ProducerConfig.<init>(ProducerConfig.java:340)
at org.apache.kafka.clients.producer.KafkaProducer.<init>(KafkaProducer.java:166)
at org.hs.My.tools.connector.MyProducerTest$$anon$1.<init>(MyProducerTest.scala:21)
at org.hs.My.tools.connector.MyProducerTest$.delayedEndpoint$org$hs$My$tools$connector$MyProducerTest$1(MyProducerTest.scala:21)
at org.hs.My.tools.connector.MyProducerTest$delayedInit$body.apply(MyProducerTest.scala:16)
at scala.Function0.apply$mcV$sp(Function0.scala:39)
at scala.Function0.apply$mcV$sp$(Function0.scala:39)
at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:17)
at scala.App.$anonfun$main$1$adapted(App.scala:80)
at scala.collection.immutable.List.foreach(List.scala:392)
at scala.App.main(App.scala:80)
at scala.App.main$(App.scala:78)
at org.hs.My.tools.connector.MyProducerTest$.main(MyProducerTest.scala:16)
at org.hs.My.tools.connector.MyProducerTest.main(MyProducerTest.scala)
我认为您可以尝试使用自己的自定义类扩展对象。
class MyKafkaProducer extends KafkaProducer[String, String]()
val mockKafkaProducer = mock[MyKafkaProducer]
或者,模拟 KafkaProducer 上方进行调用的类。像这样:
# main:
class BusinessApp {
// create a KafkaProducer
def sendMessage(msg: String) = {
kafkaProducer.send(new ProducerRecord(msg))
}
}
# tests:
val mockBusinessApp = mock[BusinessApp]
(mockBusinessApp.sendMessage _).expects("test").returns(true)
那么你就不是在嘲笑KafkaProducer的低级API。
请注意,您可以使用嵌入式 kafka,而根本不需要模拟 KafkaProducer,并且可以在测试期间生成/使用实际消息。