Testing the Manage Hosts Subcommands

Overview

Using boilerplate code that Cobra generated for our project makes it a little bit harder to write tests for our application. We gain development speed at the expense of flexibility because we’re constrained by the generator’s choices. To overcome this restriction while still benefiting from the generated code, we developed the application using action functions such as listAction() and deleteAction(). Because these functions are independent from the generated code, we have the flexibility to test them. By doing this, we 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. These functions take as input an instance of the io.Writer interface as the command’s output destination. In the main code, we use the os.Stdout type when calling the functions, so the output goes to the user’s screen. For our tests, we’ll use the type bytes.Buffer to capture the output and test it.

Updating the cmd/actions_test.go file

We start our tests by creating and editing a file named cmd/actions_test.go under our application’s cmd directory. We define the package and the import section.

For these tests, we’ll use:

  • The bytes package to use the type bytes.Buffer to capture output.
  • The fmt package for formatted output.
  • The io package to use the io.Writer interface.
  • The ioutil package to create temporary files.
  • The os package to delete temporary files.
  • The strings package to manipulate string data.
  • The testing package for the testing functionality.
  • The scan package we created before to help add items to the list for testing.

Get hands-on with 1400+ tech skills courses.