Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/cocoa/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Go 无接收器的模拟函数_Go_Testify_Go Testing - Fatal编程技术网

Go 无接收器的模拟函数

Go 无接收器的模拟函数,go,testify,go-testing,Go,Testify,Go Testing,我有文件util.go: 我正在使用authentic编写单元测试,从Foo开始。我想: 模拟助手 断言模拟帮助程序被调用1次 我在会议上看到了一些有希望的解决方案,但不确定: 方法1:将helper作为Foo的参数传递。我的疑问是:证词需要一个模拟结构来AssertNumberOfCalls,这里没有结构 方法2:为Foo创建一个结构。我的疑问是:我不知道为UTIL创建一个结构是否有意义。还需要更多重构,因为Foo的调用方需要utils结构 最好的方法是什么?如果您只想测试helper中调用的

我有文件util.go:

我正在使用authentic编写单元测试,从Foo开始。我想:

模拟助手 断言模拟帮助程序被调用1次 我在会议上看到了一些有希望的解决方案,但不确定:

方法1:将helper作为Foo的参数传递。我的疑问是:证词需要一个模拟结构来AssertNumberOfCalls,这里没有结构

方法2:为Foo创建一个结构。我的疑问是:我不知道为UTIL创建一个结构是否有意义。还需要更多重构,因为Foo的调用方需要utils结构


最好的方法是什么?

如果您只想测试helper中调用的参数,我一直在使用这种方法。同样的测试也将证明您的助手只被调用过一次

    // 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)
        }
    }

你根本不应该嘲笑。编写适当的测试。如果helper没有副作用,则无需检查它是否只调用了一次。如果有副作用:测试它们是否以预期的方式发生。看看stdlib是如何进行测试的。helper确实会对呼叫服务/DB产生副作用。我来自Java世界,在那里,依赖项将被模拟用于单元测试。我不想设置那些依赖项。当单元测试Foo时,我想模拟helper,因为我计划对helper进行单独的单元测试。Go中正确的单元测试不像Java中的单元测试那样完成。为helper编写测试,并为Foo编写测试,但除非您的Foo测试需要调用不同的helper,否则在您的情况下不需要调用,因为没有副作用:不要模拟它。真正地别说了。在Java中,这可能是正确的测试方法,也可能不是正确的测试方法,但在Go中,这不是正确的测试方法。您可以为助手编写测试。如果helper通过了测试,那么Foo也会通过。
    // 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)
        }
    }