【问题标题】:How do I pass arguments to run the test code [duplicate]如何传递参数以运行测试代码
【发布时间】:2022-11-23 13:13:35
【问题描述】:

我有两个文件 main.go 和 main_test.go

在 main.go 下

package main

import (
    "fmt"
    "os"
    "strconv"
)

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

func main() {
    a, _ := strconv.Atoi(os.Args[1])
    b, _ := strconv.Atoi(os.Args[2])

    fmt.Println(Sum(a, b))
}


在 main_test.go 下我有

package main

import (
    "flag"
    "fmt"
    "testing"
)

func TestMain(t *testing.M) {
    args1 := flag.Arg(0)
    args2 := flag.Arg(1)

    fmt.Print(args1, args2)

    os.Args = []string{args1, args2}

    t.Run()


}


我正在尝试通过 go test main_test.go -args 1 2 -v 运行 go test 但我没有得到正确的输出任何人都可以指导我如何编写用于测试主要功能的命令以使其正常运行。

【问题讨论】:

  • 你的测试没有测试任何东西。您可以捕获 stdout 进行测试(google it),或者更好的是,创建一个函数 add 接受两个数字并返回总和,然后从 main 调用它。然后你可以直接测试add
  • 谢谢@AbhijitSarkar,我是用 golang 编写单元测试的新手。在读取主函数内部的参数时,我询问了如何编写主函数的代码。

标签: go go-testing


【解决方案1】:

下面是使用传递给它的参数测试主函数的代码:

func TestMain(m *testing.M) {
    a := make([]string, len(os.Args)+2)
    a[0] = os.Args[0]
    a[1] = "first arg"
    a[2] = "second arg"
    copy(a[3:], os.Args[1:])

    os.Args = a

    main()
}

【讨论】:

    【解决方案2】:

    具有常量示例(测试用例)的测试比在测试中使用任何交互式事物更有效率,因为您可能需要它自动运行多次。你为什么不像我的例子那样做?

    main_test.go:

    package main
    
    import (
        "testing"
    )
    
    func TestMain(t *testing.T) {
    
        for _, testCase := range []struct {
            a, b, result int
        }{
            {1, 2, 3},
            {5, 6, 11},
            {10, 2, 12},
        } {
            if Sum(testCase.a, testCase.b) != testCase.result {
                t.Fail()
            }
        }
    
    }
    
    

    看看这个例子也很好: Go By Example: Testing

    【讨论】:

      猜你喜欢
      • 2012-10-26
      • 1970-01-01
      • 2016-06-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多