Go from Beginner to Expert: A Complete Guide to Learn Golang PART-23 Step-by-Step Guide on Testing Your Golang Code

Go from Beginner to Expert: A Complete Guide to Learn Golang PART-23

Step-by-Step Guide on Testing Your Golang Code

Md. Faiyaj Zaman
4 min readMar 21, 2023

--

Welcome to this tutorial on testing your Golang code. Testing is an essential part of software development, and Golang provides us with a robust testing framework.

In this tutorial, we will discuss how to write and run tests in Golang, along with some best practices for testing in Golang.

Please check the previous guide on Best practices for Golang Programming.

Writing and Running Tests in Golang

To write tests in Golang, we need to create a new file with a _test.go suffix in the same package as the code we want to test.

Let’s say we have a file named calculator.go with an Add function that takes two integers and returns their sum. We can create a new file named calculator_test.go and add a test function like this:

package main

import "testing"

func TestAdd(t *testing.T) {

result := Add(2, 3)

if result != 5 {

t.Errorf("Add(2, 3) = %d; want 5", result)

}

}

In the above code snippet, we import the testing package and create a new test function named TestAdd that takes a testing T object. We then call the Add function with two integers and compare the result with the expected value using the t.Errorf function.

To run the tests, we can use the go test command in the terminal. We navigate to the package directory and run the command go test. The output will show us whether the tests have passed or failed.

Best Practices for Testing in Golang

Here are some best practices for testing in Golang:

  1. Write tests for each function or method

It’s a good practice to write a separate test function for each function or method in your code. This helps to isolate bugs and make the tests more specific.

2. Use table-driven tests

Table-driven tests are tests that use a table of inputs and expected outputs to test a function. This is a good practice as it allows us to test multiple scenarios in one test function and makes it easy to add more test cases later.

Here’s an example of a table-driven test:

func TestMultiply(t *testing.T) {

testCases := []struct {

name string

a, b int

expected int

}{

{"2x3", 2, 3, 6},

{"-2x3", -2, 3, -6},

{"0x0", 0, 0, 0},

}

for _, tc := range testCases {

t.Run(tc.name, func(t *testing.T) {

result := Multiply(tc.a, tc.b)

if result != tc.expected {

t.Errorf("%s: Multiply(%d, %d) = %d; want %d", tc.name, tc.a, tc.b, result, tc.expected)

}

})

}

}

In the above code snippet, we define a test table with three test cases, each with a name, two input integers, and an expected output.

We then loop through the test cases and run a sub-test for each case, using the t.Run function. This allows us to see which specific test cases have failed.

  1. Use the testing t.Helper() function The t.Helper() function is used to indicate that a test function is a helper function and should not appear in the output if the test fails. This makes it easier to read the test output and identify the root cause of the failure.
  2. Use code coverage tools Code coverage tools can help us identify which parts of our code are not covered by our tests and could be potential sources of bugs. Golang provides a built-in code coverage tool, which we can use by adding the -cover flag to the go test command. This will show us the percentage of code covered by our tests.
  3. Mock dependencies When testing functions that rely on external dependencies, such as a database or an API, it’s a good practice to use mocks or stubs. This allows us to test the function in isolation without depending on the external resource.

Here’s an example of using a mock:

type mockDatabase struct{}

func (m *mockDatabase) Save(data string) error {

return nil

}

func TestSaveData(t *testing.T) {

db := &mockDatabase{}

err := SaveData("test data", db)

if err != nil {

t.Errorf("SaveData returned error: %v", err)

}

}

In the above code snippet, we define a mock database that implements the same interface as our real database. We then pass this mock database to our SaveData function, which allows us to test the function without actually saving data to the real database.

That’s it for this tutorial on testing your Golang code. We’ve covered how to write and run tests in Golang, along with some best practices for testing.

By following these best practices, you can ensure that your code is thoroughly tested and free of bugs.

Thanks for reading!

--

--