Test-driven development (TDD) sometimes takes too much time when it comes to creating an app. Whether it is a web app or a CLI app, it doesn’t matter. Being disciplined on testing is a hard thing to do. But it is a worthy investment to bet. Who knows, it will help you prevent unwanted zero-day bugs.
Besides that, creating tests will help you develop a better code. A testable code is a better code. At least that’s what I think. Because it forced you to think about the corner cases, create smaller decoupled functions, Etc. Even though it takes time, it makes your code more readable and gives only a few chances for bugs to have showtime.
Cobra also has no excuse for no tests. Even though it only helps you to create a CLI app, it needs proper testable code too. In this blog post, you will learn how to implement unit tests for Cobra.
Initialize Cobra Project
$ cobra init example --pkg-name example
Your Cobra application is ready at
$ cd example && go mod init example
go: creating new go.mod: module example
go: to add module requirements and sums:
go mod tidy
$ tree .
│ └── root.go
1 directory, 4 files
Modify Root Command
To implement a simple unit test, you can remove all the root.go file content and make it as minimum as possible. For example:
It’s up to you to choose either option 1 or 2. You can adjust it with your project. But if you want to keep the nature of the Cobra code that exposes the cmd as a variable, you can stick to option 2.
Create the Test Cases
Let’s say you stick with option 2. Now you need to create the test cases. In this case, the test cases will be either with the toggle flag or without. But first, let’s make a helper function that will execute the root command and store the output to a variable. By storing the command output to a variable, you can compare the command output with your expectations.