Mock function without receiver

落爺英雄遲暮 提交于 2020-06-28 03:57:31

问题


I have the file util.go:

func Foo(service *SomeService) error {
    return helper(service)
}

func helper(service *SomeService) error {
    ...
}

I'm writing unit tests using testify, starting with Foo. I want to:

  1. mock helper
  2. assert mocked helper was called 1 time

I saw some promising solutions at https://stackoverflow.com/a/19168875/1661745, but not sure about them:

Method 1: pass helper as parameter of Foo. My doubt: testify needs a Mock struct to AssertNumberOfCalls, and here there is no struct.

Method 2: create a struct for Foo. My doubt: I don't know if it makes sense to make a struct for utils. Also requires more refactoring since callers of Foo would need a utils struct.

What's the best way to do this?


回答1:


If you just want to test the args being called in helper, this is an approach that I have been using. The same test will also prove that your helper was called exactly once.

    // Code

    var originalFn = func(arg1, arg2 string) {
        ...
    }


    func Foo() {
        originalFn(arg1,arg2)
    }

    // Tests

    func TestFoo(t *testing.T) {
        tempFn := originalFn
        var fnArgs []string
        originalFn = func(arg1, arg2) {
            fnArgs = append(fnArgs, []string{arg1, arg2})
        }
        defer originalFn = tempFn

        tests := []struct{
            expected []string
        }{
            {
                expected: []string{"arg1", "arg2"},
            },
        }

        for _, tt:= range tests {
            fnArgs := make([]string, 0)
            Foo()
            assert.Equal(t, tt.expected, fnArgs)
        }
    }


来源:https://stackoverflow.com/questions/62208286/mock-function-without-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!