Testing Go Code

Let’s learn how to test Go code.

The subject of this lesson is the testing of Go code by writing test functions. Software testing is a very large subject and cannot be covered in a single lesson of a chapter in a course. So, this lesson tries to present as much practical information as possible.

Go allows us to write tests for our Go code to detect bugs. However, software testing can only show the presence of one or more bugs, not the absence of bugs. This means that we can never be 100% sure that our code has no bugs!

Strictly speaking, this lesson is about automated testing, which involves writing extra code to verify whether the real code—that is, the production code—works as expected or not. Thus, the result of a test function is either PASS or FAIL. We will see how this works shortly. Although the Go approach to testing might look simple at first, especially if we compare it with the testing practices of other programming languages, it is very efficient and effective because it does not require too much of the developer’s time.

We should always put the testing code in a different source file. There is no need to create a huge source file that is hard to read and maintain. Now, let us present testing by revisiting the matchInt() function from “Chapter 3, Composite Data Types.”

Writing tests for intRE.go

In this lesson, we write tests for the matchInt() function, which was implemented in intRE.go back in Chapter 3, Composite Data Types. First, we create a new file named intRE_test.go, which is going to contain all tests. Then, we rename the package from main to testRE and remove the main() function—this is an optional action. After that, we must decide what we are going to test and how. The main steps in testing include writing tests for expected input, unexpected input, empty input, and edge cases. All these are going to be seen in the code. Additionally, we are going to generate random integers, convert them to strings, and use them as input for matchInt(). Generally speaking, a good way to test functions that work with numeric values is by using random numbers, or random values in general, as input and see how our code behaves and handles these values.

The two test functions of intRE_test.go are the following:

Get hands-on with 1200+ tech skills courses.