假设我有一个简单的应用程序,它从stdin中读取行并简单地将它回显给stdout。例如:如何编写写入标准输入的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))
}
}
我想写写入stdin和然后输出与该输入测试案例。例如:
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
我明明做一些不正确这里。我应该如何去测试这种类型的代码?
我已经从输出中删除了“>”并使用了你的TestInput函数。我得到了一系列的约100个重复的失败,看起来是这样的: === RUN TestInput ---失败:TestInput(5.17s) \t echo_test.go:36:求购:ABC \t \t,得到: --- FAIL:TestInput(5.15s) \t \t \t echo_test.go:36:通缉:ABC \t \t \t \t,GOT:--- FAIL:TestInput(5.13s) \t \t \t \t \t echo_test.go :36:通缉:abc ...等等。 –
当我移除“>”时,它对我很好。你提供了正确的命令来运行? –
我将命令更改为os.Args [0]。 –