Last active
January 26, 2021 06:08
-
-
Save draveness/97612b4179009615f5a26569245fe9dc to your computer and use it in GitHub Desktop.
Monkey Patch Mock in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 {} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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()) | |
} |
func ListPosts() []Post {
JUMP XXX
// ...
}
无法对内联函数生效,需要添加 -N -l
选项关闭内联
[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
https://github.com/bouk/monkey