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

Patricia Arquette
Release: 2024-10-26 17:32:30
Original
892 people have browsed it

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!