尽管有测试功能,为什么我还是“没有测试要运行”?

She*_*ock 0 testing go

新手来这里,我写了一个简单的 main_test.go 文件来运行 main.go 的一些测试用例,当我运行go test它时说 testing:warning: no tests to run PASS ok Solution 0.878s

我的 main.go:

package main

func normalizePhoneNum(phoneNumber string) string {
    return ""
}

func main() {

}
Run Code Online (Sandbox Code Playgroud)

main_test.go:

package main

import (
    "testing"
)

func testNormalizePhoneNum(t *testing.T) {
    testCase := []struct {
        input  string
        output string
    }{
        {"1234567890", "1234567890"},
        {"123 456 7891", "123 456 7891"},
        {"(123) 456 7892", "(123) 456 7892"},
        {"(123) 456-7893", "(123) 456-7893"},
        {"123-456-7894", "123-456-7894"},
        {"123-456-7890", "123-456-7890"},
        {"1234567892", "1234567892"},
        {"(123)456-7892", "(123)456-7892"},
    }
    for _, tc := range testCase {
        t.Run(tc.input, func(t *testing.T) {
            actual := normalizePhoneNum(tc.input)
            if actual != tc.output {
                t.Errorf("for %s: got %s, expected %s", tc.input, actual, tc.output)
            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)

谁能告诉,为什么它不运行测试用例?

jub*_*0bs 5

初级!请参阅go test命令文档

一个测试函数是一个命名的TestXxxXxx不以小写字母开头)并且应该有签名,

func TestXxx(t *testing.T) { ... }
Run Code Online (Sandbox Code Playgroud)

请注意,第一个字母必须是大写T。您必须遵守此测试函数的命名约定,否则测试工具将简单地忽略它们。

将您的测试函数重命名为TestNormalizePhoneNumgo test再次尝试运行。


或者——尽管这很可能不是你想要的——你可以强制测试工具运行一个不符合命名约定的“测试函数”,方法是指定它的名称(或者,更一般地说,一个正则表达式它的名称匹配)在-run标志中:

go test -run=testNormalizePhoneNum
Run Code Online (Sandbox Code Playgroud)