Testing the Manage Hosts Subcommands
Learn how to write test cases for managing hosts subcommands.
We'll cover the following...
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
bytespackage to use the typebytes.Bufferto capture output. - The
fmtpackage for