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 年 1 月 23 日 · 2467 次点击
    这是一个创建于 2629 天前的主题,其中的信息可能已经有所发展或是发生改变。

    在写测试的时候, 有一种 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   ·   Solana   ·   2304 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 00:59 · PVG 08:59 · LAX 17:59 · JFK 20:59
    ♥ Do have faith in what you're doing.