agiledragon / gomonkey

gomonkey is a library to make monkey patching in unit tests easy
MIT License
1.93k stars 178 forks source link

couldn't mock generic function #95

Closed ericuni closed 1 year ago

ericuni commented 2 years ago

Does gomonkey support generics for now?

func GeneraicMin[T int|int32](a, b T) T {
  if a <= b {
    return a
  }
  return b
}

func TestGenericFunc(t *testing.T) {
  assert := assert.New(t)

  patches := gomonkey.ApplyFunc(GeneraicMin[int], func(a, b int) int {
    return 100
  })
  defer patches.Reset()

  got := GeneraicMin(rand.Int(), rand.Int())
  assert.Equal(100, got) // would fail
}
agiledragon commented 1 year ago

You can mock generic function by gomonkey, for example:

func Add[T int | float32 | float64](a T, b T) T {
    return a + b
}

var AddInt = Add[int]

func TestGenericPatch(t *testing.T) {
    Convey("TestGenericPatch", t, func() {
        So(AddInt(1, 2), ShouldEqual, 3)
        patches := ApplyFuncVarReturn(&AddInt, 5)
        defer patches.Reset()
        So(AddInt(1, 2), ShouldEqual, 5)
    })
}

Running tool: /usr/local/go/bin/go test -timeout 30s -run ^TestGenericPatch$ goconvey-study/slice -v -count=1 -gcflags=all=-l

=== RUN   TestGenericPatch

  TestGenericPatch ✔✔

2 total assertions

--- PASS: TestGenericPatch (0.00s)
PASS
ok      goconvey-study/slice    0.007s
agiledragon commented 1 year ago

https://www.jianshu.com/p/8a52eae7f786