Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

couldn't mock generic function #95

Closed
ericuni opened this issue Jun 23, 2022 · 2 comments
Closed

couldn't mock generic function #95

ericuni opened this issue Jun 23, 2022 · 2 comments

Comments

@ericuni
Copy link

ericuni commented Jun 23, 2022

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
Copy link
Owner

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
Copy link
Owner

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants