Go (Golang) / Testing and Debugging in Go

Using the testing Package for Assertions

In this tutorial, we'll delve deeper into the 'testing' package and learn how to use it for assertions in Go. You'll learn how to assert expected outcomes in your tests.

Tutorial 3 of 5 5 resources in this section

Section overview

5 resources

Teaches unit testing, benchmarking, and debugging techniques in Go.

1. Introduction

The purpose of this tutorial is to teach beginners how to use the testing package in Go for assertions. Assertions are statements in code that assert or state that something must be true. In Go, we use the testing package to write and run tests. These tests can include assertions to verify the program's correctness.

During the tutorial, you will learn:
- About the Go testing package
- How to write and run tests
- How to use assertions in tests

Prerequisites: Basic knowledge of Go programming. If you are a complete beginner, you might want to have a look at Go's official tutorial first.

2. Step-by-Step Guide

2.1 Writing Tests

In Go, a test is just a function with a name starting with Test followed by a word or phrase starting with a capital letter. It takes one argument, a pointer to testing.T. If the function calls a failure function such as t.Error or t.Fail, the test is considered failed.

func TestAdd(t *testing.T) {
    result := add(2, 2)
    if result != 4 {
        t.Fail()
    }
}

2.2 Running Tests

To run tests in Go, you use the go test command followed by the package name.

go test mypackage

2.3 Using Assertions

The testing package does not have built-in assertion capabilities. For this, we often use a third-party package like github.com/stretchr/testify/assert. Let's add it to our project.

go get github.com/stretchr/testify/assert

Now, we can use the assert package to make assertions in our tests.

import (
    "testing"
    "github.com/stretchr/testify/assert"
)

func TestAdd(t *testing.T) {
    result := add(2, 2)
    assert.Equal(t, 4, result, "they should be equal")
}

3. Code Examples

Let's look at a practical example.

package main

import (
    "testing"
    "github.com/stretchr/testify/assert"
)

func add(a int, b int) int {
    return a + b
}

func TestAdd(t *testing.T) {
    result := add(2, 2)
    assert.Equal(t, 4, result, "they should be equal")
}

Here we have a function add that takes two integers and returns their sum. The TestAdd function tests whether the add function works correctly. assert.Equal checks if the result equals 4.

4. Summary

In this tutorial, you've learned how to use the testing package in Go and how to use the testify package to add assertions to your tests. Now you can write tests for your functions and verify that they are working as expected.

Next steps: Learn more about test-driven development (TDD) and how it can improve your code. Also, learn about other types of tests (like benchmark tests and table-driven tests) in Go.

Additional resources:
- Go's official testing documentation
- Testify's GitHub page

5. Practice Exercises

  1. Write a function that subtracts two integers and write a test for it using an assertion.
  2. Write a function that concatenates two strings and write a test for it using an assertion. Make sure to test edge cases like empty strings.
  3. Write a function that divides two floats and write a test for it using an assertion. What happens when the divisor is 0?

Solutions:

func subtract(a int, b int) int {
    return a - b
}

func TestSubtract(t *testing.T) {
    result := subtract(5, 3)
    assert.Equal(t, 2, result, "they should be equal")
}
func concatenate(a string, b string) string {
    return a + b
}

func TestConcatenate(t *testing.T) {
    result := concatenate("Hello, ", "World!")
    assert.Equal(t, "Hello, World!", result, "they should be equal")
}
func divide(a float64, b float64) (float64, error) {
    if b == 0 {
        return 0, errors.New("Cannot divide by zero")
    }
    return a / b, nil
}

func TestDivide(t *testing.T) {
    result, err := divide(10.0, 2.0)
    assert.NoError(t, err)
    assert.Equal(t, 5.0, result, "they should be equal")
}

Tips for further practice: Try to write tests for more complex functions. Also, learn about mocking to be able to write tests for functions that depend on other functions.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Date Difference Calculator

Calculate days between two dates.

Use tool

HTML Minifier & Formatter

Minify or beautify HTML code.

Use tool

Word to PDF Converter

Easily convert Word documents to PDFs.

Use tool

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help