Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

Go Lang - Testing in Go

Introduction to Testing in Go

Testing in Go is an essential part of ensuring the reliability and correctness of your code. Go provides a built-in testing framework through the 'testing' package, which allows developers to write and execute tests easily.

Key Points:

  • The 'testing' package in Go supports writing tests using the 'go test' command.
  • Tests in Go are typically placed in files named *_test.go and follow a specific naming convention.
  • Unit tests, benchmark tests, and example tests are common types of tests supported by the 'testing' package.

Example of Testing in Go

Below is an example demonstrating testing in Go:


// Example: Testing in Go
package main

import (
    "testing"
)

// Function to be tested
func Add(a, b int) int {
    return a + b
}

// Test function for Add function
func TestAdd(t *testing.T) {
    result := Add(2, 3)
    expected := 5
    if result != expected {
        t.Errorf("Add function test failed: Expected %d, got %d", expected, result)
    }
}
          

Summary

This guide provided an introduction to testing in Go using the 'testing' package, including examples of writing and executing tests. By writing comprehensive tests for your Go code, you can ensure its reliability and maintainability throughout the development lifecycle.