Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Unit testing 在go中测试CLI参数_Unit Testing_Go_Testing_Automated Tests_Command Line Interface - Fatal编程技术网

Unit testing 在go中测试CLI参数

Unit testing 在go中测试CLI参数,unit-testing,go,testing,automated-tests,command-line-interface,Unit Testing,Go,Testing,Automated Tests,Command Line Interface,我想在go中测试一些在main()函数中运行的CLI例程,它们只是我正在做的练习,但我想对它们进行测试! 例如,我如何向表传递参数来测试这个算法之王 package main import ( "bufio" "fmt" "os" "strconv" ) func main() { var f *os.File f = os.Stdin defer f.Close() scanner := bufio.NewScanner(

我想在go中测试一些在main()函数中运行的CLI例程,它们只是我正在做的练习,但我想对它们进行测试! 例如,我如何向表传递参数来测试这个算法之王

package main


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

func main() {
    var f *os.File
    f = os.Stdin
    defer f.Close()

    scanner := bufio.NewScanner(f)

    for scanner.Scan() {
        if scanner.Text() == "STOP" || scanner.Text() == "stop" {
            break
        }

        n, err := strconv.ParseInt(scanner.Text(), 10, 64)

        if err == nil {
            fmt.Printf("Number formatted: %d\n", n)
        } else {
            fmt.Println(err.Error())
        }
    }
}
为了更好的帮助,我也把代码放在了操场上!


提前谢谢

严格地说,你不需要使用围棋。当我考虑编写CLI工具时,我会尽快脱离
main
,使用函数和结构,以通常的方式进行单元测试

为了确保所有CLI参数和文件系统but都正确插入,我一直在使用它来运行命令并检查完整构建的工具

你可以看到一个例子,我是如何做到这一点的


也许不是您想要的答案,但它对我来说一直很好。

您需要创建一个函数,将输入和输出通道作为参数。它应该读写这些参数。以下是一个例子:

梅因,加油

package main

import (
    "bufio"
    "fmt"
    "io"
    "os"
    "strconv"
)

func main() {
    var f *os.File
    f = os.Stdin
    defer f.Close()
    run (os.Stdin, f)
}

func run(in io.Reader, out io.Writer) {
    scanner := bufio.NewScanner(in)

    for scanner.Scan() {
        if scanner.Text() == "STOP" || scanner.Text() == "stop" {
            break
        }

        n, err := strconv.ParseInt(scanner.Text(), 10, 64)

        if err == nil {
            fmt.Printf("Number formatted: %d\n", n)
        } else {
            fmt.Println(err.Error())
        }
    }
}
main_test.go

package main

import (
    "bytes"
    "fmt"
    "testing"
)
func TestRun(t *testing.T){
    var command, result bytes.Buffer
    fmt.Fprintf(&command, "10\n")
    fmt.Fprintf(&command, "stop\n")
    run(&command, &result)
    got := result.String()
    //test for contents of "got"
    fmt.Println(got)
}
现在,您可以在命令行上运行以下命令

go test

您无法像现在这样很好地测试它,但提取一个可测试的函数非常容易: