首頁 > 後端開發 > 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學習者快速成長!