V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
petelin
V2EX  ›  Go 编程语言

写了一个 mock 任何 变量 的函数

  •  
  •   petelin · 2019-01-23 18:13:54 +08:00 · 2192 次点击
    这是一个创建于 1912 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在写测试的时候, 有一种 mock 方法是这样的

    var foo = func(){}
    

    这个时候可以替换 foo, 然后跑测试, 最后在还原(隔离)

    如果这么写要很长很长....

    有了 patch 方法, 只需要两行

    func TestH(t *testing.T) {
     say := func() {
      fmt.Println("say")
     }
     rec := patchFunction(&say, func() { fmt.Println("replace") })
     say()
     defer rec() # 还原
    }
    
    func patchFunction(item interface{}, new interface{}) func() {
     old := reflect.ValueOf(item).Elem().Interface()
     rec := func() {
      reflect.ValueOf(item).Elem().Set(reflect.ValueOf(old))
     }
     reflect.ValueOf(item).Elem().Set(reflect.ValueOf(new))
     return rec
    }
    

    另外求教一下, reflect.valueOf 一个 interface 拿到的直接就是里面的包的元素?? interface 内存里不是两部分吗, 我总觉得应该是 .Elem()拿到包裹的元素, 然后在.Elem().Set()改指针值.

    目前尚无回复
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3201 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 13:46 · PVG 21:46 · LAX 06:46 · JFK 09:46
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.