3

有没有办法在没有设置实际代理的情况下测试/模拟 sarama-cluster 的 NewConsumer 功能?我在这里想念什么?

我正在尝试测试的代码:

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
}
4

1 回答 1

4

不要调用 cluster.NewConsumer,而是添加一个可以在测试中换出的简单间接。例如,将函数分配给一个包变量(我用 time.Now 一直这样做)。

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")
}
于 2017-10-25T16:13:50.560 回答