【发布时间】:2017-11-16 22:40:04
【问题描述】:
我正在为我在 golang 中开发的函数编写单元测试。这是代码sn-p:
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
}
}
现在我想模拟第一个解组返回成功,第二个解组返回失败。在 python 中,我看到了一篇类似的帖子: Python mock multiple return values
但是我找不到 golang 的。谁能帮我解决这个问题。
【问题讨论】:
-
不幸的是,这在 Golang 中并不是那么简单。最好的办法是重构您的函数,以便可以强制使
json.Unmarshal返回错误,例如当调用json.Unmarshal(a, &b)并且 a 不是 json 格式时。
标签: unit-testing go mocking