Testing the Basic Word Counter

Powerful Command-Line Applications in Go — by Ricardo Gerardi (12 / 127)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Building the Basic Word Counter | TOC | Adding Command-Line Flags 👉

Go lets you test your code automatically without requiring external tools or frameworks. You’ll learn more about how to test your command-line applications throughout the book. Right now, let’s write a basic test for the word counter to ensure that it correctly counts the words in the given input.

Create a file called main_test.go in the same directory as your main.go file. Include the following content, which defines a testing function that tests the count function you’ve already defined in the main program:

firstProgram/wc/main_test.go

​ ​package​ main

​ ​import​ (
​ ​"bytes"​
​ ​"testing"​
​ )

​ ​// TestCountWords tests the count function set to count words​
​ ​func​ TestCountWords(t *testing.T) {
​ b := bytes.NewBufferString(​"word1 word2 word3 word4​​\n​​"​)

​ exp := 4

​ res := count(b)

​ ​if​ res != exp {
​ t.Errorf(​"Expected %d, got %d instead.​​\n​​"​, exp, res)
​ }
​ }

This test file contains a single test called TestCountWords. In this test, we create a new buffer of bytes from a string containing four words and pass the buffer into the count function. If this function returns anything other than 4, the test doesn’t pass and we raise an error that shows what we expected and what we actually got…

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.