Testing Cobra CLI commands in GoLang
If you have ever developed CLI with cobra then you must have faced a problem when it comes to testing it, especially sub-commands.
In order to test the sub-commands ~ you must understand that it has to go through the root/parent command.
In this quick article, we will cover two main topics:
1. Test any sub-commands
2. Test specific commands dynamically
Let’s assume that below is our commands structure:
As you can see in the diagram,
- Root is the parent command.
- A, B, and C are child commands.
- a1, a2, and, a3 are sub-commands of A.
- b1 is the sub-command of B.
After adding commands ~ It looks like this:
- Test any sub-commands:
As the name says, we would like to write a test for any sub-command reside under root command. For example, let’s write a test to assert a1 command.
Note: In line 17, you can also pass the flag with its value.
2. Test specific commands dynamically:
~> Key is to use the annotation field in the command, just like we did in A2cmd while implementing main.go (line 48)
As you can see, we have created execute() to facilitate the command run process.
This is just a basic way to run all the commands dynamically ~ There are many other things that can be achieved with annotation.
Happy brewing…