// sample-wordcount_test.go: tests for sample-wordcount.go. // Free sample from 99helpers.com/file-types/go // // Files ending in _test.go are only compiled by `go test`, never by // `go build`. Run the tests (and the example) with: // // go test -v sample-wordcount.go sample-wordcount_test.go // // and the benchmark (b.Loop needs Go 1.24 or later) with: // // go test -bench=. sample-wordcount.go sample-wordcount_test.go package main import ( "fmt" "maps" "strings" "testing" ) // A test function: its name starts with Test and it takes a *testing.T. // This one is table-driven: each case is a row, run as a named subtest. func TestCountWords(t *testing.T) { cases := []struct { name string text string want map[string]int }{ {"empty", "", map[string]int{}}, {"case folding", "Go go GO", map[string]int{"go": 3}}, {"punctuation", "one, two; two!", map[string]int{"one": 1, "two": 2}}, {"accents", "Café CAFÉ café", map[string]int{"café": 3}}, {"German", "Straße straße", map[string]int{"straße": 2}}, {"Japanese", "東京 大阪 東京", map[string]int{"東京": 2, "大阪": 1}}, {"digits", "route 66, route 66", map[string]int{"route": 2, "66": 2}}, } for _, tc := range cases { t.Run(tc.name, func(t *testing.T) { got := CountWords(tc.text) if !maps.Equal(got, tc.want) { t.Errorf("CountWords(%q) = %v, want %v", tc.text, got, tc.want) } }) } } func TestTopWordsTies(t *testing.T) { got := TopWords(map[string]int{"b": 2, "a": 2, "c": 5}, 2) want := []WordCount{{"c", 5}, {"a", 2}} if fmt.Sprint(got) != fmt.Sprint(want) { t.Errorf("TopWords = %v, want %v", got, want) } } // An example: go test runs it and compares what it prints with the // "Output:" comment. It also appears in the package's documentation. func ExampleTopWords() { counts := CountWords("to be or not to be") fmt.Println(TopWords(counts, 2)) // Output: [{be 2} {to 2}] } // A benchmark: go test -bench=. runs the loop as many times as it needs to // measure it. func BenchmarkCountWords(b *testing.B) { text := strings.Repeat("the quick brown fox jumps over the lazy dog ", 100) for b.Loop() { CountWords(text) } }