我有一个结构体
type Server struct {
grpcServerPort int
grpcServer *grpc.Server
writer *kafka.Writer
}
这个服务器有很多方法,包括-
func NewServer(port int) *Server {
server := &Server{
grpcServerPort: port,
}
gs := grpc.NewServer()
server.grpcServer = gs
return server
}
func (s *Server) StartServer() {
createKafkaTopic("brokker_url", "my_topic")
s.writer = &kafka.Writer{
Addr: kafka.TCP("urls"),
Topic: "my_topic",
Balancer: &kafka.Hash{},
MaxAttempts: 1,
BatchSize: 1,
}
listener, err := net.Listen("tcp", fmt.Sprintf(":%d", s.grpcServerPort))
if err != nil {
fmt.Printf("failed to listen: %v", err)
}
go s.grpcServer.Serve(listener)
}
func (s *Server) produceEvents(key string, val string) error {
msg := kafka.Message{
Key: []byte(key),
Value: []byte(val),
}
err = s.writer.WriteMessages(context.Background(), msg)
if err != nil {
return err
}
return nil
}
现在createTopic如果在我的机器上没有启动和运行kafka代理,则方法panic。我想知道如何模拟createTopic和produceEvents这样我就可以为服务器的其他方法编写单元测试用例。
我上周才遇到你的案子。我是这样解决的:
type KafkaWriter interface {
Method001fKafkaWriter()
Method002fKafkaWriter()
}
type Server struct {
grpcServerPort int
grpcServer *grpc.Server
writer KafkaWriter
}
现在,你可以用接口
模拟Kafka的依赖关系type mockKafkaWriter struct {
}
func (*mockKafkaWriter) Method001fKafkaWriter() {}
func (*mockKafkaWriter) Method002fKafkaWriter() {}
我希望这能帮助你!
您可以定义一个接口,然后定义一个模拟结构体来实现它,现在您可以测试它了。
type Server struct {
grpcServerPort int
grpcServer *grpc.Server
writer KafkaWriterWrapper
}
type KafkaWriterWrapper interface {
Write(msg string) error // Suppose kafka.Writer has func Write(msg string) error
}
type KafkaWriterWrapperImpl struct {
*kafka.Writer
}
type MockKafkaWriterWrapperImpl struct {
}
func (m *MockKafkaWriterWrapperImpl) Write(msg string) error {
// logic
return nil
}