Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@husobee
Created March 3, 2015 20:33
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save husobee/9ff87a6f27e9abb4a3bc to your computer and use it in GitHub Desktop.
Save husobee/9ff87a6f27e9abb4a3bc to your computer and use it in GitHub Desktop.
Example of Mocking in Golang, and Monkey Patch
package main
import "fmt"
type Something struct {}
func (s Something) Test() bool {
return false
}
type SomethingInterface interface {
Test() bool
}
type MockSomething struct {
MockTest func() bool
}
func (ms MockSomething) Test () bool {
if ms.MockTest != nil {
return ms.MockTest()
}
return false
}
func main() {
regularSomething := Something{}
mockSomething := MockSomething{
MockTest: func() bool {
// this is where your mock happens
return true
},
}
fmt.Println("result of do something is: ",
doSomething(regularSomething))
fmt.Println("result of mocked do something is: ",
doSomething(mockSomething))
// now a patch example
oldDoSomething := doSomething
// reset func after completing method
defer func () { doSomething = oldDoSomething}()
doSomething = func(s SomethingInterface) bool {
return true
}
// monkey patched version of doSomething will return true,
// instead of what it should return, false.
fmt.Println("result of do something is: ",
doSomething(regularSomething))
}
var doSomething = func(s SomethingInterface) bool {
return s.Test()
}
@jabielecki
Copy link

Nitpick about the naming. "Monkey patching" proper is forcefully modifying the compiled machine code, either on disk or in memory. (There are a few Go modules for that.) I'm struggling however to find a better name for that pattern with doSomething var. Maybe "monkey substitution"?

@yeukhon
Copy link

yeukhon commented Sep 19, 2022

@jabielecki I think you want to call this a stub.

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