gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 01:18:26 30 4
gpt4 key购买 nike

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

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

我显然在这里做了一些不正确的事情。我应该如何测试此类代码?

最佳答案

您可以定义一个接受io.Reader 和一个 io.Writer 作为参数并做任何你想让它做的事情。 main 然后可以调用该函数,您的测试函数可以直接测试该函数。

关于unit-testing - 如何编写写入标准输入的 Go 测试?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37256859/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com