3

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?

user844541
  • 2,868
  • 5
  • 32
  • 60
  • 1
    I don't know gomock, but 2 and 3 seem legit. I think 2 would result in cleaner code. However, if you can alter the server's API to return an error from Send, it would be both healthier for your application, and easier to verify - make MockServer check the messages and return an error if it's not valid. Not returning errors from operations that can fail is a design flaw. – Not_a_Golfer Jan 30 '15 at 10:27

1 Answers1

2

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.

Ainar-G
  • 34,563
  • 13
  • 93
  • 119