Home  >  Article  >  Backend Development  >  How to Test Go Code that Reads from Stdin and Writes to Stdout?

How to Test Go Code that Reads from Stdin and Writes to Stdout?

Patricia Arquette
Patricia ArquetteOriginal
2024-10-27 05:20:03855browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn