Home >Backend Development >Golang >How to Test Go Code that Reads from Stdin and Writes to Stdout?
Writing Go Tests for Code that Writes to Stdin
To write a Go test for code that reads from stdin and echoes it back to stdout, it's advisable to isolate the functionality into a separate function that takes an io.Reader and an io.Writer as parameters.
Instead of performing all operations in the main function using stdin and stdout directly, your code should define a function for this specific purpose. For instance:
<code class="go">func echo(r io.Reader, w io.Writer) { reader := bufio.NewReader(r) for { fmt.Print("> ", w) bytes, _, err := reader.ReadLine() if err == io.EOF { os.Exit(0) } fmt.Println(string(bytes), w) } }</code>
Within your main function, you can then call the echo function:
<code class="go">func main() { echo(os.Stdin, os.Stdout) }</code>
To test this function, you can create a test like this:
<code class="go">import ( "bytes" "io" "testing" ) func TestEcho(t *testing.T) { input := "abc\n" expected := "abc\n" r := bytes.NewBufferString(input) w := bytes.NewBufferString("") echo(r, w) if got := w.String(); got != expected { t.Errorf("Expected: %v, Got: %v", expected, got) } }</code>
This test creates a buffered reader from the specified input string and a buffered writer to capture the output. It then calls the echo function, passing in the reader and writer. Finally, it compares the output with the expected result.
The above is the detailed content of How to Test Go Code that Reads from Stdin and Writes to Stdout?. For more information, please follow other related articles on the PHP Chinese website!