【问题标题】:go tests cases aren't running in main packagego 测试用例没有在主包中运行
【发布时间】:2019-09-21 14:22:59
【问题描述】:

我正在尝试编写一个简单的测试来更好地理解 golang 测试,但测试用例似乎没有执行,我预计它会失败。

在我的main.go 我有:

package main

import "fmt"

func main() {
    fmt.Println("run")
}

func twoSum(nums []int, target int) []int {
    lookup := make(map[int]int)
    for i, n := range nums {
        c := target - n
        if j, ok := lookup[c]; ok {
            return []int{j, i}
        }
        lookup[n] = i
    }
    return []int{}
}

然后在我的main_test.go 我有这个:

package main

import (
    "reflect"
    "testing"
)

var twoSumsCases = []struct{
    input []int
    target int
    expected []int

} {
    {
         []int{2,7,11,15},
         9,
         []int{0,3},

    },
}

func TesttwoSum(t *testing.T) {

    for _, tc := range twoSumsCases {
        actual := twoSum(tc.input, tc.target)

        eq := reflect.DeepEqual(actual, tc.expected)

        if eq {
            t.Log("expected: ", tc.expected, " actual: ", actual)
        } else {
            t.Error("expected: ", tc.expected, " actual: ", actual)

        }
    }
}

然后当我运行go test -v...它告诉我testing: warning: no tests to run。我以此为例:https://blog.alexellis.io/golang-writing-unit-tests/...and 我想我得到了我需要的一切,但不确定为什么测试没有执行。

【问题讨论】:

    标签: go


    【解决方案1】:

    将测试函数的名称更改为TestTwoSum。此名称与testing package documentation 第一段中描述的模式相匹配:

    ...它旨在与“go test”命令一起使用,该命令自动执行表单的任何功能

    func TestXxx(*testing.T)
    

    其中 Xxx 不以小写字母开头。 ...

    【讨论】:

      【解决方案2】:

      尝试将测试函数重命名为:

      func TestTwoSum(t *testing.T) {
      

      Golang 测试非常区分大小写。测试函数需要使用以“Test”开头的 Pascal Case 命名,以便go test 工具可以发现它。

      【讨论】:

        猜你喜欢
        • 2017-09-10
        • 2012-02-15
        • 1970-01-01
        • 2017-01-16
        • 2017-04-29
        • 2014-07-06
        • 2014-04-08
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多