testify icon indicating copy to clipboard operation
testify copied to clipboard

Use function pointers to set up mock expectations

Open littledot opened this issue 7 years ago • 9 comments

testify provides the On() function to set up mock expectations, which uses a string to identify the mocked function. However, Go provides an API runtime.FuncForPC() which allows users to obtain a function pointer's name.

type Sap struct {
}

func (i *Sap) Magic() {
	fmt.Println("Magic")
}

func dump(a interface{}) {
	name := runtime.FuncForPC(reflect.ValueOf(a).Pointer()).Name()
	fmt.Println(name)
}

func main() {
	dump((*Sap).Magic) // "main.(*Sap).Magic"
	s := &Sap{}
	dump(s.Magic) // "main.(*Sap).Magic-fm"
	sa := Sap{}
	dump(sa.Magic) // "main.(*Sap).Magic-fm"
}

https://play.golang.org/p/RAB0zOkB0L

What are your thoughts on providing a new API similar to On() which accepts function pointers in the form of interface{} instead of string? The implementation would then parse the function pointer's name to identify the method that needs mocking. I think this could really reduce pains in refactoring code - such as method renaming - because tools can now pick up these tokens.

littledot avatar Apr 07 '17 04:04 littledot

👍

tartale avatar May 09 '17 23:05 tartale

sounds great, as well as I need a feature to On() receive a function pointer as a parameter

wuxinwei avatar Mar 06 '18 13:03 wuxinwei

I'm really interested in this. The issue is old. Do you know if anyone implemented it somewhere may be a fork ?

I can try to implement it in few weeks

The current implementation is a bit frustrating for me when I refactor code with my IDE, the string used everywhere are not updated, and I have to manually edit tons of files.

ccoVeille avatar Aug 11 '22 10:08 ccoVeille

based on a quick code check, I think the code needed to implement it is close to what is currently in (m *Mock) Called

ccoVeille avatar Aug 11 '22 10:08 ccoVeille

for further reading: https://stackoverflow.com/questions/7052693/how-to-get-the-name-of-a-function-in-go

ccoVeille avatar Aug 11 '22 10:08 ccoVeille

but I don't plan to work on it, until someone confirms it's not already implemented somewhere

ccoVeille avatar Aug 11 '22 10:08 ccoVeille