Shoulder.dev Logo Shoulder.dev

How do I add Tests to this codebase? - benhall/golang-demo

How do I add Tests to this codebase?

Go has a built-in testing framework, go test. To write tests, you need to create files that end with _test.go. This tells the go test command to execute them as tests.

Example: Testing a function

// main.go
package main

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

// main_test.go
package main

import "testing"

func TestSum(t *testing.T) {
    result := Sum(2, 3)
    if result != 5 {
        t.Errorf("Sum(2, 3) = %d; want 5", result)
    }
}

The above code shows a simple example of a function Sum and its corresponding test. In main_test.go, the TestSum function uses the t.Errorf method to report a failure if the result of Sum(2, 3) is not equal to 5.

Running Tests

To run the tests, use the go test command in the directory containing your Go package.

go test

This will execute all the test files in the directory and print the results.

Other Test Functions

The testing package provides several methods for reporting test failures and successes:

  • t.Errorf(format string, args ...interface{}): Reports a test failure with an error message.
  • t.Fatalf(format string, args ...interface{}): Reports a test failure and halts the current test.
  • t.Logf(format string, args ...interface{}): Logs an informational message.
  • t.Skip(format string, args ...interface{}): Skips the current test and reports it as skipped.

Example: Using t.Fatalf

func TestDivisionByZero(t *testing.T) {
    _, err := Divide(10, 0)
    if err == nil {
        t.Fatalf("Divide(10, 0) should return an error")
    }
}

In this example, t.Fatalf is used to report a fatal error if the Divide(10, 0) function does not return an error.

Writing More Complex Tests

For more complex tests, you can use testing.T methods like t.Run to group tests and t.Parallel to run tests concurrently.

Example: Using t.Run and t.Parallel

func TestSumWithMultipleInputs(t *testing.T) {
    t.Run("positive numbers", func(t *testing.T) {
        result := Sum(2, 3)
        if result != 5 {
            t.Errorf("Sum(2, 3) = %d; want 5", result)
        }
    })

    t.Run("negative numbers", func(t *testing.T) {
        t.Parallel()
        result := Sum(-2, -3)
        if result != -5 {
            t.Errorf("Sum(-2, -3) = %d; want -5", result)
        }
    })
}

In this example, t.Run is used to create two separate tests, one for positive numbers and one for negative numbers. The t.Parallel method indicates that the test for negative numbers can be run concurrently with other tests.

By following these guidelines and using the testing package, you can effectively write and run tests for your Go code.