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() != "fake return output" { t.Fatalf("failed" + 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.Replace(s, "b", "c", -1) } func TestFiles(t *testing.T) { tests := []struct { testName string oldConfigVal string newConfigVal string err error }{ {"Testing First config", `a:b`, `a:c`, nil}, {"Tesing second config", `e:f`, `e:f`, nil}, } t.Run("Test config replaced correctly", func(t *testing.T) { for _, tc := range tests { t.Run(tc.testName, func(t *testing.T) { res := rep(tc.oldConfigVal) t.Log(res, tc.newConfigVal) if res != tc.newConfigVal { t.Errorf("unable to read file") } }) } }) }

October 2, 2021 · 1 min · Nolan