Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.