WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

Go · Intermediate · question 36 of 100

How do you write unit tests in Go?

📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

To write unit tests in Go, you need to follow a specific naming convention and structure for your test files and functions. Additionally, you will be using the ‘testing‘ package provided by the Go standard library.

Here are the steps to write a simple unit test in Go:

1. Create a new test file with the same name as the file you want to test, but with a ‘_test.go‘ suffix. If your file is named ‘math.go‘, your test file should be ‘math_test.go‘.

2. Import the ‘testing‘ package at the beginning of the test file.

3. Write test functions that follow the naming convention ‘TestXxx(t *testing.T)‘, where ‘Xxx‘ is the name of the function you want to test.

4. Use the ‘t‘ testing object to perform assertions and report any errors by calling its ‘Error‘ or ‘Errorf‘ methods.

5. Run ‘go test‘ in your terminal to execute your tests.

Here’s an example for writing unit tests for a simple ‘Add‘ function defined in a file ‘math.go‘:

File: ‘math.go‘

package main

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

File: ‘math_test.go‘

package main

import (
    "testing"
)

func TestAdd(t *testing.T) {
    cases := []struct {
        a, b, expected int
    }{
        {1, 2, 3},
        {4, 6, 10},
        {-1, 2, 1},
        {-4, -6, -10},
    }

    for _, tc := range cases {
        result := Add(tc.a, tc.b)
        if result != tc.expected {
            t.Errorf("Add(%d, %d) = %d; expected %d", tc.a, tc.b, result, tc.expected)
        }
    }
}

In this example, we have defined a ‘TestAdd‘ function with various test cases, and then performed the assertions checking the returned result of the ‘Add‘ function against the expected values.

To run these tests, execute the command ‘go test‘ in your terminal. If all tests pass, you will see a message like ‘PASS‘, otherwise, you will see the error messages reported by the ‘t.Errorf‘ method.

You can use other methods from the ‘*testing.T‘ struct like ‘t.Fatal‘ or ‘t.Fatalf‘ when you want to stop the execution of the test immediately after reporting an error.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic Go interview — then scores it.
📞 Practice Go — free 15 min
📕 Buy this interview preparation book: 100 Go questions & answers — PDF + EPUB for $5

All 100 Go questions · All topics