title: How To Mock Out KafkaProducer Used Inside a Scala Class
body: <p>I want to write a unit test for a Scala class.  The purpose of the class is to collect metrics and post them on a Kafka topic.  I am trying to mock the producer in the unit test to ensure sanity of the rest of the code.  Below is a simplified version of my class:</p>
  
  <pre><code>class MyEmitter(sparkConf: SparkConf) {
      &lt;snip&gt; -- member variables
      private val kafkaProducer = createProducer()
  
  def createProducer(): Producer[String, MyMetricClass] = {
      val props = new Properties()
      ...
      Code to initialize properties
      ...
  
      new KafkaProducer[String, MyMetricClass](props)
  }
  
  def initEmitter(metricName: String): SomeClass = {
      // Some implementation
  }
  
  def collect(key: String, value: String): Unit = {
      // Some implementation
  }
  
  def emit(): Unit = {
      val record = new ProducerRecord("&lt;topic name&gt;", "&lt;key&gt;", "&lt;value&gt;")
      kafkaProducer.send(record)
  }
  </code></pre>
  
  <p>What I would like to do in my unit test is to mock out the producer and check whether the <em>send()</em> command has been called and, if so, whether the producer record matches the expectation.  I have been unsuccessful to find a solution on my own.  Googling the solution has also been unfruitful.  If anyone knows how the problem could be solved, I will be most grateful.</p>