What is Unit Testing?
The first step is to comprehend what unit testing means. Unit testing refers to the process of testing small code units or modules to ensure that each of them functions as expected. Unit testing is used to remove problems from code, improve code stability, and ensure correctness when updating code. The initial stage of software testing is the unit test, which is followed by the UI test and integration test.
The Testing Package
In Golang, unit testing is performed using a package called testing. The package provides various functions that allow us to test our code. The Go code can be automatically tested with the help of the testing package.
Example Program to Test
We need some code for our tests to analyze before we can write any unit tests. We will create a small program that adds two numbers.
import (
"fmt"
)
funcAdd(a int, b int) int {
return a + b
}
func main() {
fmt.Println(Add(2, 3))
}
The above code defines the Add() function, which adds two numbers, a and b, as inputs and outputs the result as an integer. Adding the numbers 2 and 3 is all that the main function does before printing the outcome.
Convention of Writing Unit Tests in the Go
Every Go project should have a separate test file that contains all the tests for that project. The file should have the same name as the file being tested and should have _test.go added to the end of the filename. For example, if we want to test a file named calculator.go, we should name our test file calculator_test.go.
It’s standard practice for Go testing files to be located in the same package or directory as the code they are evaluating. When you use the go build command, the compiler does not create these files, so you don’t have to be concerned about their showing up in deployments.
To write a unit test in Go, we need to use the testing package. We can start each test function with the word Test and then add a description of what we want to test. For example, TestAddition or TestSubtraction. We can then write the test code that checks whether the function we are testing returns the expected results.
In Go, each test function should start with the statement t := testing.T{}. This statement creates a new testing object that we can use to check whether the test has passed or failed. We can then use the t.Errorf() function to print an error message if the test fails.
How to Write the Testing Code?
When it comes to writing unit tests in Go, it is important to begin by specifying the package that you wish to test. After importing the testing package, you can access various types and methods that the package exports, including the testing.T type. The testing logic itself is then written in a function that starts with the keyword “Test” followed by a descriptive name, such as TestAdd(). Within this function, you can include the code for the test and any assertions needed to verify the expected behavior.
To sum up, the characteristics of a test in Go are as follows:
- The single and only required parameter is t *testing.T
- The testing function begins with the word Test and is then followed by a word or phrase that begins with a capital letter.
- To indicate a failure, the testing function should call either t.Errorf or t.Fail, and to provide additional debug information without causing a failure, t.Log can be used.
- To deliver non-failing debug information, employ t.Log.
- Tests are stored in files with the name foo_test.go, for example, math_test.go.
Close the file after saving it.
import (
"testing"
)
funcTestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}
The Add() function is tested by the TestAdd() function, which is defined in this test. It uses the numbers 2 and 3 to call Add, and then it confirms that the outcome is 5. An error message is printed if the result is less than 5 when t.Errorf() is invoked.
Finally, it is important to know that Go has a built-in testing tool called go test. This tool runs all the tests in the project and provides a report of the results. Go test must be typed in the terminal while in the project directory to start the tests. All of the tests in that directory will run as a result.
Results of Unit Test
The output will show you the test functions that passed, failed, or skipped.
PASS or OK denotes that the code is operating as intended. You will receive FAIL if a test fails.
The _test.go suffix is the only one that the go test subcommand checks for in files. Afterward, go test searches those file(s) for any special functions, such as func TestXxx and several others. Go test builds and calls these functions correctly, executes them, gathers, and reports the results, and finally cleans up everything in a temporary main package.
The last step is to integrate your tests into your development workflow. The best practice is to run your tests each time you commit your code to a repository. The integration of your tests into your development workflow ensures that your code is continuously tested, and any issues are resolved before deployment.
Conclusion
Writing unit tests is a crucial component of software development because it guarantees that your code is scalable, functional, and effective. The Go testing library is effortless and straightforward to use. You should be able to create Golang unit tests of the highest quality by following the procedures listed above. Remember to integrate your tests into your development workflow to ensure that your code is continuously tested, and any issues are resolved before deployment.