Testing the Manage Hosts Subcommands

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

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Creating the Subcommands to Mana ge Hosts | TOC | Adding the Port Scanning Function ality 👉

Using boilerplate code that Cobra generated for your project makes it a little bit harder to write tests for your application. You gain development speed at the expense of flexibility since you’re constrained by the generator’s choices. To overcome this restriction while still benefiting from the generated code, you developed the application using action functions such as listAction and deleteAction. Because these functions are independent from the generated code, you have the flexibility to test them. By doing this, you won’t be testing the part of the code generated by Cobra, but this is acceptable because we trust it was tested by Cobra’s developers.

The action functions accept the parameters required to test them properly. You’re using the same pattern you used before in Using Interfaces to Automate Tests. These functions take as input an instance of the io.Writer interface as the command’s output destination. In the main code, you use the os.Stdout type when calling the functions, so the output goes to the user’s screen. For your tests, you’ll use the type bytes.Buffer to capture the output and test it.

Start your tests by creating and editing a file cmd/actions_test.go under your application’s cmd directory. Define the package and the import section…

--

--

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.