我有一个像这样的 Go 代码
func (r *Request) SetRequestMap(ctx *gin.Context, data map[string]interface{}) *Request {
//Some processing code
id, ok := r.map["id"]
if !ok {
return r
}
checkStatus := checkStatusOnline(ctx, id) // checkStatusOnline returns "on" if id is present or "off".
// It make use of HTTP GET request internally to check if id is present or not.
// All json unmarshal is taken care of internally
if checkStatus == "on" {
r.map["val"] = "online"
}
return r
}
我想为 SetRequestMap
编写单元测试用例.我如何模拟
checkStatusOnline
没有为模拟实现任何额外的功能?
最佳答案
模拟此类函数的一种方法是使用函数指针:
var checkStatusOnline = defaultCheckStatusOnline
func defaultCheckStatusOnline(...) {... }
在测试运行期间,您可以设置 checkStatusOnline
到不同的实现来测试不同的场景。func TestAFunc(t *testing.T) {
checkStatusOnline=func(...) {... }
defer func() {
checkStatusOnline=defaultCheckStatusOnline
}()
...
}
关于go - 模拟非接口(interface)函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63016942/