Using Interfaces to Automate Tests

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Adding Temporary Files to the Markdown Preview Tool | TOC | Adding an Auto-Preview F eature 👉

Sometimes you need a way to test output printed out to STDOUT. In this instance, when executing the integration tests, by testing the run function, the name of the output file is created dynamically. The function prints this value to the screen so the user can use the file, but to automate tests, we need to capture this output from within the test case.

In Go, the idiomatic way to deal with this situation is by using interfaces, in this case io.Writer, to make your code more flexible. For this pattern, we update the function run so that it takes the interface as an input parameter. We do this so we can call run with different types that implement the interface depending on the situation: for the program, we use os.Stdout to print the output onscreen; for the tests, we use bytes.Buffer to capture the output in a buffer that we can use in the test.

To start, include the io package in the import section in order to use the io.Writer interface:

workingFiles/mdp.v2/main.go

​ ​import​ (
​ ​"bytes"​
​ ​"flag"​
​ ​"fmt"​

» ​"io"​
​ ​"io/ioutil"​
​ ​"os"​

​ ​"github.com/microcosm-cc/bluemonday"​
​ ​"github.com/russross/blackfriday/v2"​
​ )

--

--

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.