首页 > 后端开发 > Golang > 正文

如何测试从 Stdin 读取的 Go 应用程序:模拟读取器和写入器指南

Patricia Arquette
发布: 2024-10-26 17:32:30
原创
892 人浏览过

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

测试写入 Stdin 的 Go 应用程序

本指南演示如何编写与 stdin 读取应用程序交互的 Go 测试用例。考虑下面的示例应用程序:

<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>
登录后复制

创建测试用例

为了测试此应用程序的 stdin 功能,我们定义一个从 io.Reader 读取的单独函数并写入 io.Writer:

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

修改 main 函数

在 main 函数中,我们以 stdin 和 stdout 作为参数调用 testFunction:

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

编写测试用例

在我们的测试用例中,我们现在可以使用模拟 io.Reader 和 io.Writer 直接测试 testFunction:

<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>
登录后复制

通过使用这种方法,您可以有效地测试写入 stdin 的应用程序,将测试逻辑与主函数中错综复杂的 stdin 和 stdout 管理隔离开来。

以上是如何测试从 Stdin 读取的 Go 应用程序:模拟读取器和写入器指南的详细内容。更多信息请关注PHP中文网其他相关文章!

来源:php.cn
本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
作者最新文章
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责声明 Sitemap
PHP中文网:公益在线PHP培训,帮助PHP学习者快速成长!