【问题标题】:Can't stub with Kafka producer record in Spock无法在 Spock 中使用 Kafka 生产者记录存根
【发布时间】:2018-08-16 18:39:21
【问题描述】:

我正在尝试使用 Spock 对一些 Kafka 代码进行单元测试,但在对 KafkaProducer.send() 函数的响应进行存根处理时遇到问题。这是我需要绕过的 Java 代码行:

Object out = producer.send(record).get()

这是我的 Spock 代码:

given:
Object obj = new Object()
KafkaProducer producer = kafkaProducerService.getProducer()

when:
kafkaProducerService.publish(someData)

then:
1 * producer.send(_ as ProducerRecord).get >> obj

我得到的错误是:

org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object '_' with class 'org.spockframework.lang.Wildcard' to class 'org.apache.kafka.clients.producer.ProducerRecord' due to: groovy.lang.GroovyRuntimeException: Could not find matching constructor for: org.apache.kafka.clients.producer.ProducerRecord(org.spockframework.lang.SpreadWildcard)

我什至用producer.send(_).get() >> obj 尝试了完整的通配符路由,但这也不起作用(使用ProducerRecord 的建议非常令人沮丧):

groovy.lang.MissingMethodException: No signature of method: org.apache.kafka.clients.producer.KafkaProducer.send() is applicable for argument types: (org.spockframework.lang.Wildcard) values: [[*_]]
Possible solutions: send(org.apache.kafka.clients.producer.ProducerRecord), send(org.apache.kafka.clients.producer.ProducerRecord, org.apache.kafka.clients.producer.Callback), find(), find(groovy.lang.Closure), any(), sleep(long)

ProducerRecord 不是抽象的,不是接口,而且肯定有构造函数,那又是什么呢?

【问题讨论】:

    标签: java unit-testing apache-kafka spock


    【解决方案1】:

    问题似乎在于您的验证以及您链接了两个方法调用 (.send().get()) 的事实。因此 spock 不会在 send 上运行验证,而是在 get 上运行验证,并且不识别通配符语法。你可能需要这个:

    given:
    def sendResult = Mock(Future)
    ...
    
    then:
    1 * producer.send(_ as ProducerRecord) >> sendResult
    1 * sendResult.get() >> obj
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2016-06-16
      • 2021-10-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多