Use function pointers to set up mock expectations

Open
#425 10 comments 9 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Assessment

Difficulty
5/5
Estimated time
Over a week
Newbie friendliness
32/100
Issue type
Feature
Clarity
Needs clarification
Activity status
Stale
Tech stack
go
Domain
testing

Research direction

Start by reading testify's existing On() API and the Go runtime.FuncForPC() example in the issue. Determine whether a function-pointer-based expectation API is feasible and agree on how method names should be identified; done requires a defined API and behavior that supports the refactoring use case.

Written by the indexing model from the issue text.

Description

enhancement pkg-mock

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.

Dominant language
Go
Stars
26.2k
Forks
1.9k
Avg merge
2d 4h
Merged PRs (30d)
2

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

More from stretchr/testify

All issues in stretchr/testify

Similar issues

More Go issues

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.