learn-golang-with-tdd

Notes about the things I learnt while reading/practicing with Learn Go with Tests.

[TOC]


Hello, World

What I learned

Few rules to writing tests

godoc and the PATH

# installing local documentation
go install golang.org/x/tools/cmd/godoc@latest

# after installing the godoc command isn't available
# in the path! I had to call it via:
~/.asdf/installs/golang/1.21.7/packages/bin/godoc -http :8000

Starting a module

create the hello module:

mkdir hello
cd hello
go mod init hello
# check if the "go.mod" file was created

hello.go:

package main

import "fmt"

// Hello() is a separated function
// to make it testable
func Hello() string {
  return "Hello, world"
}

func main() {
  fmt.Println(Hello())
}

hello_test.go:

package main

import "testing"

func TestHello(t *testing.T) {
  got := Hello()
  want := "Hello, world"

  if got != want {
    t.Errorf("got %q want %q", got, want)
  }
}

Run the test:

go test

integers

Testable Examples

official docs

func ExampleAdd() {
	sum := Add(1, 5)
	fmt.Println(sum)
	// Output: 6
}

iterations

for loops

benchmarking

This goes in the repeat_test.go file:

func BenchmarkRepeat(b *testing.B) {
  for i := 0; i < b.N; i++ {
    Repeat("a")
  }
}

The code is very similar to a test.

The testing.B gives you access to the cryptically named b.N.

When the benchmark code is executed, it runs b.N times and measures how long it takes.

The amount of times the code is run shouldn't matter to you, the framework will determine what is a "good" value for that to let you have some decent results.

To run the benchmarks do go test -bench=.

$ go test -bench=.
goos: darwin
goarch: arm64
pkg: iteration
BenchmarkRepeat-8       15226100                79.48 ns/op
PASS
ok      iteration       2.719s

The test was executed 15,226,100 times. Each execution took on average 79.42 nanoseconds to run.