Passing mock as argument in Golang test

Viewed 27

This is the code I am testing

func listObjects(cli *client.Client, options clientOptions) ([]BlobObjects, error) {
    objects, err := cli.ListBlobObjects(...)
}

In my test setup I do this

type MockClient struct {
    MockListBlobObjects func() ([]BlobObjects, error)
}

func (m *MockClient) ListBlobObjects(....) ([]BlobObjects, error) {
    // return some mock response
}

And this is my test case

func TestBlobObjects(t *testing.T) {
    tests := map[string]struct {
        client         *MockClient
        ...
    }{
        "Test case 1": {
            client: &MockClient{
                MockListBlobObjects: ....,
            },
            ....
        },

      ....
   for testName, test := range tests {
      blobs, err := (test.client, clientOptions{})
      // make assertions here
   }

The problem is test.client. Compiler is telling me

cannot use test.client (variable of type *MockClient) as *client.Client value in argument to listObjects

My hope was I have a mock client and if I call the function under test, then the mock client passed will call the mocked listObjects. This is how I would do in Python.

What should I do in Golang?

1 Answers

You need to create a common interface, which will be implemented by both types

type Client interface {
    ListBlobObjects func() ([]BlobObjects, error)
}

type RealClient struct {
}

func (c *RealClient) ListBlobObjects(....) ([]BlobObjects, error) {
    // return some response
}

type MockClient struct {
  // note: don't put method signature in function body
}

func (m *MockClient) ListBlobObjects(....) ([]BlobObjects, error) {
    // return some mock response
}

and then

var client client.Client
client = &RealClient{}
// or
client = &MockClient{}
Related