Go to Learn Go

0-using-doc

godoc -http :8000
  • Packages : http://localhost:8000/pkg
  • Tests examples : http://localhost:8000/pkg/testing/

1-hello-world

Writing a test is just like writing a function, with a few rules

  • It needs to be in a file with a name like xxx_test.go (your code file is xxx.go)
  • The test function must start with the word Test
  • The test function takes one argument only t *testing.T

Examples

hello.go

func Hello() string {
	return "Hello, world"
}

hello_test.go

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

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

In Go, we can declare function inside function. Doing that, we should use T.Helper().

func TestHello(t *testing.T) {
	assertCorrectMessage := func(t *testing.T, got, want string) {
    t.Helper() // t.Helper() is needed to tell the test suite that
    // this method is a helper. By doing this when it fails the line
    // number reported will be in our function call rather
    // than inside our test helper. 
		if got != want {
			t.Errorf("got %q want %q", got, want)
		}
	}

	t.Run("saying hello to people", func(t *testing.T) {
		got := Hello("Chris")
		want := "Hello, Chris"
		assertCorrectMessage(t, got, want)
	})

	t.Run("empty string defaults to 'World'", func(t *testing.T) {
		got := Hello("")
		want := "Hello, World"
		assertCorrectMessage(t, got, want)
	})
}

To keep it simpler, we can mark as comment what we expect in the test. In this example, test will fail if it is different from 6.

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

The development cycle

  • Write a test
  • Make the compiler pass
  • Run the test, see that it fails and check the error message is meaningful
  • Write enough code to make the test pass
  • Refactor

Naming

  • Public functions starts with an capital letter
  • Private fucntions starts with a lowercase

3-iterations

Benchmarks

Writing benchmarks in Go is another first-class feature of the language and it is very similar to writing tests.

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

To launch benchmarks : go test -bench=.

4-arrays-slice

Arrays have a fixed capacity which you define when you declare the variable. We can initialize an array in two ways:

  • [N]type{value1, value2, ..., valueN} := [5]int{1, 2, 3, 4, 5}
  • [...]type{value1, value2, ..., valueN} := [...]int{1, 2, 3, 4, 5}

❤️ Tips

  • ARRAY is a an array with encoded size (e.g int[4])
  • SLICE does not encode the size (e.g int[])

Create an array with make and a given size

sums := make([]int, lengthOfNumbers)