Home >Backend Development >Golang >Unit testing of golang functions

Unit testing of golang functions

WBOY
WBOYOriginal
2024-04-20 09:48:02705browse

Unit tests test individual functions or small pieces of logic to ensure that modified code still runs as expected. Practical examples include writing functions, creating test files, defining test cases, and reporting test failures using t.Errorf. Best practices include writing tests for every function, using meaningful test case names, testing a variety of inputs, running tests frequently, and keeping tests simple.

Unit testing of golang functions

Unit testing of Go language functions

Introduction

Unit testing is the process of testing a single function or small piece of logic in a code base . They help ensure that code still runs as expected after modification and reduce the risk of introducing bugs.

Practical Case

Consider the following function, which calculates the sum of two numbers:

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

To test this function, we can create a test file and use testing Package:

import (
    "testing"
)

func TestSum(t *testing.T) {
    // 创建测试用例
    testCases := []struct {
        a, b, expected int
    }{
        {1, 2, 3},
        {3, 5, 8},
        {-1, -2, -3},
    }

    for _, tc := range testCases {
        // 运行函数并获取结果
        result := Sum(tc.a, tc.b)

        // 检查结果是否等于预期值
        if result != tc.expected {
            t.Errorf("预期 %d,但得到 %d", tc.expected, result)
        }
    }
}

Run the tests

Compile and run the tests using the following command:

go test

If all tests pass, you will see output like this:

PASS
ok      github.com/username/mypackage  0.004s

Best Practice

  • Write a test function for each function or block of logic.
  • Use meaningful test case names.
  • Test various inputs and edge cases.
  • Use t.Errorf to report test failures.
  • Keep tests simple and easy to understand.
  • Run tests frequently to ensure the correctness of your code.

The above is the detailed content of Unit testing of golang functions. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn