如何在Golang中模拟函数以获得不同的返回值

huangapple go评论88阅读模式
英文:

How to mock a function to get a different return value in golang

问题

我正在为我在golang中开发的一个函数编写单元测试。以下是代码片段:

func myFunc() {
    // 一些代码
    err := json.Unmarshal(a, &b)
    if err != nil {
        // 处理错误
    }

    // 更多代码

    err := json.Unmarshal(c, &d)
    if err != nil {
        // 处理错误
    }
}

现在我想模拟第一个Unmarshal返回成功,第二个Unmarshal返回失败。在Python中,我看到了一个类似的帖子:Python模拟多个返回值

但是我找不到golang的类似方法。有人可以帮我吗?

英文:

I'm writing unit tests for a function that I developed in golang. Here is the code snippet:

func myFunc () {
    //there is some code
    err := json.Unmarshal (a, &b)
    if err != nil {
        //handle error    
    }

    //there is some more code

    err := json.Unmarshal (c, &d)
    if err != nil {
        //handle error    
    }
}

Now I want to mock first unmarshal to return success and second unmarshal to return failure. In python, I see one similar post:
Python mock multiple return values

But I cannot find one for golang. Can anyone please help me on this.

答案1

得分: 2

在这种情况下,我会使用一个导出的包变量Unmarshaller,并在init()方法中将其设置为json.Unmarshal

var Unmarshaller func(data []byte, v interface{}) error;

func init() {
    Unmarshaller = json.Unmarshal
}

然后,当你想要强制出错时,你可以这样做:

mypackage.Unmarshaller = func(data []byte, v interface{}) error {
    return errors.New("It broke!")
}

然后,在你的代码中,不再直接调用json.Unmarshal,而是调用你的包级别的Unmarshaller,所以

err := json.Unmarshal(jsonBytes, &test)

将变为

err := Unmarshaller(jsonBytes, &test)

这是一个简短的示例:https://play.golang.org/p/CinLmprtp5

英文:

What I would do in this situation is have an exported package variable Unmarshaller and set it to json.Unmarshal in the init() method.

var Unmarshaller func(data []byte, v interface{}) error;

func init() {
    Unmarshaller = json.Unmarshal
}

Then, when you want to force an error, you can just do

mypackage.Unmarshaller = func(data[] byte, v interface{}) error {
    return errors.New("It broke!")
}

Then, in your code, instead of calling json.Unmarshal directly, you call your package level `Unmarshaller, so

err =: json.Unmarshal(jsonBytes, &test)

would become

err =: Unmarshaller(jsonBytes, &test)

As a short example: https://play.golang.org/p/CinLmprtp5

huangapple
  • 本文由 发表于 2017年6月15日 00:50:42
  • 转载请务必保留本文链接:https://go.coder-hub.com/44550509.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定