简体   繁体   中英

Unable to stub a Class with overloaded constructors - Scalamock

I am trying to stub a class called 'Producer' with the following signature:

class Producer[K, V](private val underlying : kafka.producer.Producer[K, V]) extends scala.AnyRef {
  def this(config : kafka.producer.ProducerConfig) = { /* compiled code */ }
  def send(message : kafka.producer.KeyedMessage[K, V]) : scala.Unit = { /* compiled code */ }
  def send(messages : java.util.List[kafka.producer.KeyedMessage[K, V]]) : scala.Unit = { /* compiled code */ }
  def close : scala.Unit = { /* compiled code */ }
}

the code val fakeProducer = stub[Producer[String, String]]

Following is the error: 在此处输入图片说明

I have been stuck with this issue for sometime now. Is there a way we can create this stub object? Any help would be appreciated.

Best Regards.

Not an exact answer as I don't have an IDE right now, and not sure which version of scalamock, kafka, scala you use but hopefully this gives you an idea that works.

I would subclass your type to mock and be explicit which constructor the subclass refers to.

class MockableProducer extends kafka.javaapi.producer.Producer[String, String](null.asInstanceOf[kafka.producer.Producer[String,String])
val producer = stub[MockableProducer]

Be aware that all sideeffects of the Producer class will still run when the stub is created, which can give some unexpected NPEs

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