doufen3563 2017-06-14 13:22
浏览 86
已采纳

如何在Golang中使用成员函数正确模拟结构?

I have two structs: FunctionalityClient and TestClient, both implementing Interface. I have a global variable Client of type Interface. I assign to Client either the actual client, or the mock client, depending on whether it's a test or a normal run.

Interface has a method Request that I want to mock in tests. That is, I want to:

  • record what were the argument passed to the function
  • return some arbitrarily defined return value from the function

So the struct looks like this:

type TestClient struct {
     recordedArgs []interface{}
     returnValues []interface{}
}
func (c *TestClient) Request(body io.Reader, method string, endpoint string, headers []Header) ([]byte, error) {
    c.recordedArgs = append(c.recordedArgs, []interface{}{body, method, endpoint, headers})  // this can't be typed if I want the code to be reusable
        if len(c.returnValues) != 0 {
        last := c.returnValues[0]
        c.returnValues = c.returnValues[1:]
        return last.([]byte), nil
    }
    return nil, nil
}

And I use it like so:

testClient := TestClient{
    returnValues: []interface{}{
        []byte("arbitrarily defined return value"),
        []byte("this will be returned after calling Request a second time"),
    }
}
Client = &testClient
// run the test
// now let's check the results
r1 := testClient.recordedArgs[1].([]interface{})  // because I append untyped lists to recordedArgs
assert.Equal(t, "POST", r1[1].(string))
assert.Equal(t, "/file", r1[2].(string))
// and so on

Now the question.

I have a few structs that I want to mock like this. Currently I just copy and paste the code above for each struct. But that really sucks, I would like the mock logic to be abstracted away somehow. I would also accept something like Mockito's when: when the mocked function is called with specific arguments, return a specific value and record the call.

How can I properly mock a struct with member functions in Golang?

  • 写回答

1条回答 默认 最新

  • doudouchan5830 2017-06-14 13:49
    关注

    If you're mocking out clients for HTTP APIs, you might want to just use httptest.Server, which would simplify this tremendously. Rather than mocking out the client, mock out the server the client connects to. It's really easy to use, and you can still record the request method, path, body, etc., as well as returning arbitrary response values the same way you're doing with the mock client.

    If that's not an option, you can abstract out your mock method to make it reusable:

    type TestClient struct {
         recordedArgs [][]interface{}
         returnValues []interface{}
    }
    
    func (c *TestClient) mock(args ...interface{}) interface{} {
        c.recordedArgs = append(c.recordedArgs, args)
        if len(c.returnValues) != 0 {
            last := c.returnValues[0]
            c.returnValues = c.returnValues[1:]
            return last
        }
        return nil
    }
    
    func (c *TestClient) Request(body io.Reader, method string, endpoint string, headers []Header) ([]byte, error) {
        return c.mock(body,method,endpoint,headers).([]byte), nil
    }
    

    This cuts your usage-specific method down to one line.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥15 Oracle触发器记录修改前后的字段值
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题