如何在Go中测试函数调用的期望结果

huangapple go评论85阅读模式
英文:

How to test call expectation in Go

问题

我有一个名为MyClass的类需要测试。

MyClass有一个void方法,该方法调用内部服务器执行某些操作。

func (d *MyClass) SendToServer(args) {
  // 做一些事情...
  server.Send(myMessage)
}

我想模拟服务器调用Send方法,但由于该方法是一个void方法,我无法确定是否正确调用了它。

以下是我考虑的几种选项:

  1. 使用gomock,模拟服务器,并对服务的send方法设置期望。
  2. 创建自己的MockServer,并通过一系列验证来“覆盖”Send方法。类似于:
func (d *MockedServer) Send(message) {
  // 验证消息...
}
  1. 创建自己的MockServer,但不是在方法内部验证期望,而是将消息添加到消息列表中,然后验证列表的内容。

在Go语言中,哪种方法更好?

英文:

I have a class MyClass that I want to test.

MyClass has a void method that calls an inner server to do something.

func (d *MyClass) SendToServer(args)
  do stuff....
  server.Send(myMessage)

I want to mock the server call Send, but since the method is a void method I can't be sure that I am actually calling it right.

These are the options I had in mind:

  1. Use gomock, mock the server, and set expectations on the send method of the service
  2. create my own MockServer, and "override" the method Send with a bunch of verifications. Something like:

func (d *MockedServer) Send(message)
// verify message...

  1. create my own MockServer, but instead of verifying the expectation within the method, add the message to a list of messages, and then verify the content of the list.

What is a better approach in Go?

答案1

得分: 2

你可以像这样将你的方法封装成一个函数:

var sendToServer = (*Server).Send

func (d *MyClass) SendToServer(args) {
    // ...
    sendToServer(server, msg)
    // ...
}

在你的测试中可以这样使用:

func TestMyClass_SendToServer(t *testing.T) {
    // ...
    sent := false
    sendToServer = func(*Server, args) {
        sent = true
    }
    mc.SendToServer(args)
    if !sent {
        t.Error("fail")
    }
}

这个技巧在Andrew Gerrand的Testing Techniques talk中有详细介绍。

英文:

You could make a function out of your method like this:

var sendToServer = (*Server).Send

func func (d *MyClass) SendToServer(args) {
    // ...
    sendToServer(server, msg)
    // ...
}

And in your tests:

func TestMyClass_SendToServer(t *testing.T) {
    // ...
    sent := false
    sendToServer = func(*Server, args) {
        sent = true
    }
    mc.SendToServer(args)
    if !sent {
        t.Error("fail")
    }
}

This is described in Andrew Gerrand's Testing Techniques talk.

huangapple
  • 本文由 发表于 2015年1月30日 17:49:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/28233174.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定