Search code examples
gomockingapache-kafkaginkgosarama

Mocking NewConsumer in sarama-cluster


Is there a way to test/mock sarama-cluster's NewConsumer function without having actual brokers set up? What am I missing here?

Code I'm trying to test:

import cluster "github.com/bsm/sarama-cluster"

func initSaramaConsumer() (*cluster.Consumer, error) {
  brokers := []string{"some_url:port"}
  groups := "some_group"
  topics := []string{"some_topic"}
  config := cluster.NewConfig()

  saramaConsumer, err := cluster.NewConsumer(
    brokers, groups, topics, config,
  )

  if err != nil {
    return nil, err
  }

  return saramaConsumer, nil
}

Solution

  • Don't call cluster.NewConsumer, but add a simple indirection that you can swap out in tests. For instance, assign the function to a package variable (I do this with time.Now all the time).

    package main
    
    import (
        "testing"
    
        "github.com/bsm/sarama-cluster"
    )
    
    var newConsumer = cluster.NewConsumer // replaceable in tests
    
    func initSaramaConsumer() (*cluster.Consumer, error) {
        brokers := []string{"some_url:port"}
        groups := "some_group"
        topics := []string{"some_topic"}
        config := cluster.NewConfig()
    
        saramaConsumer, err := newConsumer(
                brokers, groups, topics, config,
        )
    
        if err != nil {
                return nil, err
        }
    
        return saramaConsumer, nil
    }
    
    func TestInitSaramaConsumer(t *testing.T) {
        newConsumer = newMockConsumer
        defer func() { newConsumer = cluster.NewConsumer }()
    
        // Tests for initSaramaConsumer goes here
    }
    
    func newMockConsumer([]string, string, []string, *cluster.Config) (*cluster.Consumer, error) {
        panic("not implemented")
    }