Writing Tests for Goci

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Handling Errors | TOC | Defining a Pipeline 👉

The goci tool executes tasks on a Go project. To write tests for it, we need to create a few small Go programs. Let’s start with two test cases, one for a successful build and one for a failed build so we can test the error handling. Create a directory testdata under your project directory to hold the files required for the testing. When building goci any files under this directory are ignored. In addition, create two subdirectories under testdata to hold the code for each case: tool and toolErr:

​ ​$ ​​mkdir​​ ​​-p​​ ​​$HOME/pragprog.com/rggo/processes/goci/testdata/{tool,toolErr}​

Switch to the newly created testdata/tool directory and initialize a new dummy module for this project:

​ ​$ ​​cd​​ ​​$HOME/pragprog.com/rggo/processes/goci/testdata/tool​
​ ​$ ​​go​​ ​​mod​​ ​​init​​ ​​testdata/tool​
​ go: creating new go.mod: module testdata/tool

Now, create a basic Go library to serve as test subject. Add a file add.go under testdata/tool with the following content:

processes/goci.v1/testdata/tool/add.go

​ ​package​ add

​ ​func​ add(a, b ​int​) ​int​ {
​ ​return​ a + b
​ }

Verify that you can build testdata/tool/add.go without any errors:

​ ​$ ​​go​​ ​​build​

--

--

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.