Monkey Patching in Golang

Monkey Patching As I’ve seen monkey patching is not advise in golang but it is possible here is a simple example. Code to test: package main var version = func(test string) string { return "true version" + test } func getVersion() string { return version("test") } Test package main import ( "testing" ) func TestVersion(t *testing.T) { oldfunction := version defer func() { version = oldfunction }() version = func(name string) string { return "fake return output" } if getVersion() !...

September 27, 2022 · 1 min · Nolan

Go testing

Testing in golang Simple test in go package main import "testing" func add(a, b int) int { return a + b } func TestAddingNumber(t *testing.T) { res := add(1, 7) if res != 8 { t.Errorf("Sum is incorrect, got: %d, expected: %d", res, 8) } } Run tests: go test -v ./... Avoiding repeating tests Instead of duplicating code for similar tests, there is a different way to test. package main import ( "strings" "testing" ) func rep(s string) string { return strings....

October 2, 2021 · 1 min · Nolan