ruk·si

Go
Monkey Patching

Updated at 2013-11-12 09:03

Monkey patching can be helpful in testing if you have written your program the way it can be used.

package main

import "fmt"

var userAuth = func(user string, password string) bool {
    // ... Do some real check
    return false
}

func sayHi(user string, password string) {
    if !userAuth(user, password) {
        fmt.Printf("Not logged in!\n")
        return
    }
    fmt.Printf("Hello %s!\n", user)
}

func main() {
    // Replace authentication.
    userAuth = func(string, string) bool { return true }
    sayHi("Joe", "Right Password")

    // Replace authentication again.
    userAuth = func(string, string) bool { return false }
    sayHi("Joe", "Wrong Password")
}

Sources