3

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
}
ntfx
  • 113
  • 7

1 Answers1

4

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")
}
Peter
  • 29,454
  • 5
  • 48
  • 60
  • Thank you for the answer! It would work with `*testing.T`, but I forgot to mention that I'm using `ginkgo` testing framework. Is it possible to write a test with it, probably with refactoring? – ntfx Oct 26 '17 at 08:33
  • 1
    The framework doesn't matter; I'm just illustrating the concept. Ginkgo has BeforeEach() and AfterEach(), for instance. – Peter Oct 26 '17 at 08:34
  • *mind blown* yeah, it works! Thanks a lot @Peter, I feel like I've learned a lot about go from this! – ntfx Oct 26 '17 at 11:55