Skip to content

Instantly share code, notes, and snippets.

@draveness
Last active January 26, 2021 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save draveness/97612b4179009615f5a26569245fe9dc to your computer and use it in GitHub Desktop.
Save draveness/97612b4179009615f5a26569245fe9dc to your computer and use it in GitHub Desktop.
Monkey Patch Mock in Golang
package service
import (
pwi "pkg-without-interface"
)
type service struct {}
func (s *service) ListPosts() []Post {
posts := pwi.ListPosts() // ListPosts is a pkg function.
// ...
return posts
}
type Post struct {}
package service
import (
"testing"
"bou.ke/monkey"
)
func TestListPosts(t *testing.T) {
guard := monkey.Patch(pwi.ListPosts, func() []Post {
fmt.Println("what the hell?") // what the *bleep*?
// ...
return []Post{}
})
defer guard.Unpatch()
serivce := &service{}
assert.Equal(t, []Post{}, service.ListPosts())
}
@lazywhite
Copy link

[root@control-plane monkey]# go run -N -l main.go
flag provided but not defined: -N
usage: go run [build flags] [-exec xprog] package [arguments...]
Run 'go help run' for details.

-N -1 not working, golang-1.14

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment