不带接收器的模拟功能 [英] Mock function without receiver

查看:43
本文介绍了不带接收器的模拟功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有文件 util.go :

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

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

我从 Foo 开始使用 testify 编写单元测试.我要:

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

  1. 模拟 helper
  2. 断言被嘲弄的 helper 被调用了1次
  1. mock helper
  2. assert mocked helper was called 1 time

我在 https://stackoverflow.com/a/19168875/1661745 上看到了一些有前途的解决方案,但不确定关于他们:

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

方法1:将帮助程序作为 Foo 的参数传递.我的疑问:作证需要AssertNumberOfCalls的Mock结构,这里没有结构.

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

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

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?

推荐答案

如果您只想测试 helper 中被调用的args,这就是我一直在使用的一种方法.相同的测试还将证明您的助手被准确地调用过一次.

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

这篇关于不带接收器的模拟功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆