Created
March 3, 2015 20:33
-
-
Save husobee/9ff87a6f27e9abb4a3bc to your computer and use it in GitHub Desktop.
Example of Mocking in Golang, and Monkey Patch
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 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
@jabielecki I think you want to call this a stub.