猿问

如何编写写入标准输入的 Go 测试?

假设我有一个简单的应用程序,它从标准输入读取行并将其简单地回显到标准输出。例如:


package main


import (

    "bufio"

    "fmt"

    "io"

    "os"

)


func main() {

    reader := bufio.NewReader(os.Stdin)

    for {

        fmt.Print("> ")

        bytes, _, err := reader.ReadLine()

        if err == io.EOF {

            os.Exit(0)

        }

        fmt.Println(string(bytes))

    }

}

我想编写一个写入标准输入的测试用例,然后将输出与输入进行比较。例如:


package main


import (

    "bufio"

    "io"

    "os"

    "os/exec"

    "testing"

)


func TestInput(t *testing.T) {

    subproc := exec.Command(os.Args[0])

    stdin, _ := subproc.StdinPipe()

    stdout, _ := subproc.StdoutPipe()

    defer stdin.Close()


    input := "abc\n"


    subproc.Start()

    io.WriteString(stdin, input)

    reader := bufio.NewReader(stdout)

    bytes, _, _ := reader.ReadLine()

    output := string(bytes)

    if input != output {

        t.Errorf("Wanted: %v, Got: %v", input, output)

    }

    subproc.Wait()

}

跑步go test -v给了我以下信息:


=== RUN   TestInput

--- FAIL: TestInput (3.32s)

    echo_test.go:25: Wanted: abc

        , Got: --- FAIL: TestInput (3.32s)

FAIL

exit status 1

我显然在这里做错了什么。我应该如何测试这种类型的代码?


心有法竹
浏览 166回答 2
2回答

牛魔王的故事

您可以定义一个函数,该函数将 an和 an作为参数并执行您希望它执行的任何操作,而不是main使用stdinand执行所有操作。然后可以调用该函数,您的测试函数可以直接测试该函数。stdoutio.Readerio.Writermain

FFIVE

这是一个写入标准输入并从标准输出读取的示例。请注意,它不起作用,因为输出首先包含“>”。不过,您可以修改它以满足您的需求。func TestInput(t *testing.T) {    subproc := exec.Command("yourCmd")    input := "abc\n"    subproc.Stdin = strings.NewReader(input)    output, _ := subproc.Output()    if input != string(output) {        t.Errorf("Wanted: %v, Got: %v", input, string(output))    }    subproc.Wait()}
随时随地看视频慕课网APP

相关分类

Go
我要回答