哈喽!今天心血来潮给大家带来了《如何编写写入标准输入的 Go 测试?》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到golang,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!
问题内容
假设我有一个简单的应用程序,它从标准输入读取行并将其简单地回显到标准输出。例如:
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
我显然在这里做错了什么。我应该如何测试这种类型的代码?
正确答案
这是一个写入标准输入并从标准输出读取的示例。请注意,它不起作用,因为输出首先包含“>”。不过,您可以修改它以满足您的需求。
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()
}
理论要掌握,实操不能落!以上关于《如何编写写入标准输入的 Go 测试?》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!
本文内容来源于互联网,如有侵权请联系删除。
