英文:
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
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论