Introduction
In the previous articles, we
- Created a CLI application using Go and Cobra
- Restructured the code to be extensible, maintainable, and unit testable
In this article, we will write unit tests for our CLI application. Let's get started.
Unit Test- Root Command
In the cmd/greeter directory, create a new file called root_test.go. As the name implies, this file will hold the unit test for the root command. Add the following test to the file.
I have added inline code comments so that the code is self-explanatory.
Unit Test - Greet Command
Next, we create another file called greet_test.go into the cmd/greeter directory. As the name implies, this file will hold the unit test for the greet command. Add the following test to the file.
As earlier, I have added inline code comments so that the code is self-explanatory.
To run the tests, head over to the terminal, execute the following command, and see a similar output.
Conclusion
We have successfully added initial unit tests for both- root and greet commands of our CLI application. As your application grows, it becomes even more essential to have unit tests in place to test if the business logic is working as expected. Next, we will see how to add required and optional flags to a command.