samedi 26 mai 2018

Override Go Method in Tests

So I have this Client struct that has a method UserByID that makes a HTTP request to an endpoint for a User. I want to unit test this function but also not make an actual HTTP request in the function c.Request. I want to stub that function with a response and error I can control.

func (c Client) UserByID(id string) (u User, err error) {
  v := url.Values{}
  v.Set("id", id)
  opts := Request{
    HTTP: http.Request{
        Method: http.MethodGet,
        Form:   v,
    },
    URL: 'some/endpoint/users',
  }
  resp, err := c.Request(opts)
  err = json.Unmarshal(resp, &u)
  return
}

Here's what the stub looks like:

type mockClient struct {
  Client
  fakeUser  User
  fakeError error
}

func (mc mockClient) Request(opts Request) (resp []byte, err error) {
  resp, err = json.Marshal(mc.fakeUser)
  err = mc.fakeError
  return
}

In a single test I have something like:

client := mockClient{
  fakeUser: User{},
  fakeError: nil,
}
user, err := client.UserByID(c.id)

Then I can assert the return values from client.UserByID. In this example I'm trying to override the client.Request function but I understand Go is not an inheritance-type of language. In my tests, my mockClient.Request function is not being called. The original client.Request is still being called.

I then assume that my approach is not right then. How can I test client.UserByID without actually calling the real client.Request function within it? Should the design of my methods be different?

Aucun commentaire:

Enregistrer un commentaire