在 sarama-cluster 中模拟 NewConsumer
Mocking NewConsumer in sarama-cluster
有没有办法在不设置实际代理的情况下 test/mock 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
}
不要调用 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")
}
有没有办法在不设置实际代理的情况下 test/mock 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
}
不要调用 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")
}