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.

    评论

报告相同问题?