How to Unit Test a CLI in Go?
In this post, we will learn about writing unit tests for a CLI created with Cobra in Go.
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 post, we will write unit tests for our CLI application. Let’s get started.
In case you prefer following along a video, you can checkout the following video on my YouTube channel.
root
, and greet
command in their own packages. However, both approaches are correct. You may pick one as per your use case.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.
|
|
In case you prefer following along a video, you can checkout the following video on my YouTube channel.
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.
Executing Tests
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 - the root
and the greet
command 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.