Testing the Initial CLI Implementation

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Creating the Initial To-Do Command-Line Tool | TOC | Handling Multiple Command-Line Options 👉

You can use different approaches to test your CLI tool. Since we already executed unit tests when developing the to-do API, we don’t need to repeat them here. Our CLI implementation is a wrapper around the API. Let’s leverage some of Go’s features and write integration tests instead. This way we’re testing the user interface of the tool instead of the business logic again.

One of the main benefits of Go is that it provides tools for automating the execution of tests out of the box; no additional frameworks or libraries are required. Since you write tests using Go itself, you can use any resources and features available with the language to write your test cases. In this case we will use the os/exec package, which lets us execute external commands. You’ll learn more about this package in Chapter 6, Controlling Processes.

For this test suite, we need to accomplish two main goals:

  • Use the go build tool to compile the program into a binary file.
  • Execute the binary file with different arguments and assert its correct behavior.

The recommended way for executing extra setup before your tests is by using the TestMain function. This function helps you control the extra tasks required…

--

--

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.