Site is currently on development mode

Acceptance testing your Go CLI

Last updated 1 year ago by William Martin


I’m a fan of Acceptance Test Driven Development, or Double-Loop TDD. This involves writing a failing high level end-to-end test that desires some feature, then following the red-green-refactor cycle through layers of unit tests until the acceptance test passes, and then repeating for the next feature.

I’m also a fan of Go and CLI tools. No diagram necessary.

Given these statements, it’s important for me to able to write a test suite that will exercise my CLIs in a black-box manner. Even if you don’t write your tests first, it is still extremely important to have confidence that if you changed the internals (and you do refactor don’t you?!), there are no regressions.

Fortunately, Ginkgo and it’s preferred matching library Gomega have our backs. The gexec library allows us to:

compile go binaries, start external processes, send signals and wait for them to exit, make assertions against the exit code, and stream output into**gbytes.Buffer**s to allow you make assertions against output.

So let’s start testing a simple CLI (we’ll call this scratchpad), that we expect to print “Hello World” on stdout and exit with the status code 0. For our acceptance tests, we will need to:

  • Compile the binary
  • Run the built binary as a process
  • Assert that “Hello World” appears on the stdout stream
  • Assert that the process exits with the status code 0

Here’s an example of how that might look using ginkgo and gomega:

Read full Article