The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
petelin

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

  •  
  •   petelin · Jan 23, 2019 · 2589 views
    This topic created in 2684 days ago, the information mentioned may be changed or developed.

    在写测试的时候, 有一种 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()改指针值.

    No Comments Yet
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2794 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 127ms · UTC 15:00 · PVG 23:00 · LAX 08:00 · JFK 11:00
    ♥ Do have faith in what you're doing.