Home >Backend Development >Golang >How to Test Go Applications That Read from Stdin: A Guide with Mock Readers and Writers

How to Test Go Applications That Read from Stdin: A Guide with Mock Readers and Writers

Patricia Arquette
Patricia ArquetteOriginal
2024-10-26 17:32:30964browse

How to Test Go Applications That Read from Stdin: A Guide with Mock Readers and Writers

Testing Go Applications that Write to Stdin

This guide demonstrates how to write Go test cases that interact with stdin-reading applications. Consider the example application below:

<code class="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))
    }
}</code>

Creating a Test Case

To test this application's stdin functionality, we define a separate function that reads from an io.Reader and writes to an io.Writer:

<code class="go">func testFunction(input io.Reader, output io.Writer) {
    // Your test logic here...
}</code>

Modifying the main function

In the main function, we call the testFunction with stdin and stdout as arguments:

<code class="go">func main() {
    testFunction(os.Stdin, os.Stdout)
}</code>

Writing the Test Case

In our test case, we can now directly test the testFunction using a mock io.Reader and io.Writer:

<code class="go">func TestInput(t *testing.T) {
    input := "abc\n"
    output := &bytes.Buffer{}

    inputReader := bytes.NewReader([]byte(input))
    testFunction(inputReader, output)

    if got := output.String(); got != input {
        t.Errorf("Wanted: %v, Got: %v", input, got)
    }
}</code>

By using this approach, you can effectively test applications that write to stdin, isolating the testing logic from the intricacies of stdin and stdout management in the main function.

The above is the detailed content of How to Test Go Applications That Read from Stdin: A Guide with Mock Readers and Writers. 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