Home  >  Article  >  Backend Development  >  How to use table-driven testing method in Golang unit testing?

How to use table-driven testing method in Golang unit testing?

WBOY
WBOYOriginal
2024-06-01 09:48:57567browse

Table-driven testing simplifies test case writing in Go unit tests by defining inputs and expected outputs through tables. The syntax includes: 1. Define a slice containing the test case structure; 2. Loop through the slice and compare the results with the expected output. In the actual case, a table-driven test was performed on the function of converting string to uppercase, and go test was used to run the test and print the passing result.

如何在 Golang 单元测试中使用表驱动的测试方法?

How to use table-driven testing method in Golang unit testing?

Table-driven testing is a testing method that uses a table to define multiple inputs and expected outputs. This simplifies and speeds up the process of writing test cases since we only need to define the table itself instead of writing a separate function for each test case.

Syntax

The table-driven test syntax is as follows:

import "testing"

func TestTableDriven(t *testing.T) {
    tests := []struct {
        input    string
        expected string
    }{
        {"a", "A"},
        {"b", "B"},
        {"c", "C"},
    }

    for _, test := range tests {
        result := UpperCase(test.input)
        if result != test.expected {
            t.Errorf("Expected %q, got %q", test.expected, result)
        }
    }
}
  • tests is a structure slice that defines the input to be tested and expected output.
  • range tests Loops over each test case in the tests slice.
  • result is the output of the function to be tested.
  • if result != test.expected Check if the result matches the expected output.

Practical Case

The following is a table-driven test of a function that converts a string to uppercase:

import (
    "testing"
    "strings"
)

func TestUpperCase(t *testing.T) {
    tests := []struct {
        input    string
        expected string
    }{
        {"a", "A"},
        {"b", "B"},
        {"c", "C"},
    }

    for _, test := range tests {
        result := strings.ToUpper(test.input)
        if result != test.expected {
            t.Errorf("Expected %q, got %q", test.expected, result)
        }
    }
}

To run the test, use go test:

go test -v

This will print the following output:

=== RUN   TestUpperCase
--- PASS: TestUpperCase (0.00s)
PASS
ok      github.com/user/pkg   0.005s

The above is the detailed content of How to use table-driven testing method in Golang unit testing?. 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