GOLANG: UNIT TESTING
Unit Testing made easy in Go
In this article, we will learn about unit testing in Go. Go provide built-in functionality to test your Go code. Hence, we don’t need an expensive setup or 3rd party libraries to create unit tests.
--
Like cells are the building units of our body, likewise, unit components make up software. Similarly, as the functioning of our body depends on the absolute efficiency and reliability of these cells, efficiency, and reliability of a piece of software depends on efficiency, and reliability of the unit components that makes it up.
So what are these unit components? They can be functions, structs, methods and pretty much anything that end-user might depend on. Hence, we need to make sure, whatever the inputs to these unit components are, they should never break the application.
So how we can test the integrity of these unit components? By creating unit tests. A unit test is a program that tests a unit component by all possible means and compares the result to the expected output.
So what can we test? If we have a module or a package, we can test whatever exports are available in the package (because they will be consumed by the end-user). If we have an executable package, whatever units we have available within the package scope, we should test it.
Let’s see how a unit test looks like in Go.
import "testing"func TestAbc(t *testing.T) {
t.Error() // to indicate test failed
}
This is the basic structure of a unit test in Go. The built-in testing
package is provided by the Go’s standard library. A unit test is a function that accepts the argument of type *testing.T
and calls the Error (or any other error methods which we will see later) on it. This function must start with Test
keyword and the latter name should start with an uppercase letter (for example, TestMultiply
and not Testmultiply
).
Let’s first work old fashioned executable package in $GOPATH
. I have created a greeting
package which we will use to print some greeting messages.