假设我有一个简单的应用程序,它从标准输入读取行并将其简单地回显到标准输出。例如:package mainimport ( "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 mainimport ( "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)FAILexit status 1我显然在这里做错了什么。我应该如何测试这种类型的代码?
2 回答
牛魔王的故事
TA贡献1830条经验 获得超3个赞
您可以定义一个函数,该函数将 an和 an作为参数并执行您希望它执行的任何操作,而不是main使用stdinand执行所有操作。然后可以调用该函数,您的测试函数可以直接测试该函数。stdoutio.Readerio.Writermain
FFIVE
TA贡献1797条经验 获得超6个赞
这是一个写入标准输入并从标准输出读取的示例。请注意,它不起作用,因为输出首先包含“>”。不过,您可以修改它以满足您的需求。
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()
}
- 2 回答
- 0 关注
- 165 浏览
添加回答
举报
0/150
提交
取消
