Say that I have a simple application that reads lines from stdin and simply echoes it back to stdout. For example:
package main
import (
\"bufio\"
\
Instead of doing everything in main
with stdin
and stdout
, you can define a function that takes an io.Reader
and an io.Writer
as parameters and does whatever you want it to do. main
could then call that function and your test function could test that function directly.
Here is an example that writes to stdin and reads from stdout. Note that it does not work because the output contains "> " at first. Still, you can modify it to suit your needs.
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()
}