dtdh11647 2015-01-30 09:49
浏览 16

如何在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条回答 默认 最新

  • douyi9787 2015-01-30 10:31
    关注

    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.

    评论

报告相同问题?

悬赏问题

  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答
  • ¥15 win11 23H2删除推荐的项目,支持注册表等