首頁 > 後端開發 > Golang > 主體

如何測試從 Stdin 讀取的 Go 應用程式?

Patricia Arquette
發布: 2024-10-26 13:27:30
原創
752 人瀏覽過

How to Test Go Applications That Read from Stdin?

使用標準輸入測試 Go 應用程式

在 Go 中,測試從標準輸入讀取的應用程式可能具有挑戰性。考慮一個將 stdin 輸入回顯到 stdout 的簡單應用程式。雖然看起來很簡單,但編寫驗證輸出的測試案例可能會帶來困難。

嘗試失敗

最初的方法是使用管道模擬 stdin 和 stdout並手動寫入標準輸入管道。但是,這可能會導致競爭條件和意外失敗。

解決方案:提取邏輯並測試獨立函數

而不是使用stdin 和在main 函數中執行所有操作stdout,創建一個單獨的函數,接受io. Reader 和io.Writer 作為參數。這種方法允許主函數呼叫該函數,而測試函數直接測試它。

重構程式碼

<code class="go">package main

import (
    "bufio"
    "fmt"
    "io"
)

// Echo takes an io.Reader and an io.Writer and echoes input to output.
func Echo(r io.Reader, w io.Writer) {
    reader := bufio.NewReader(r)
    for {
        fmt.Print("> ")
        bytes, _, _ := reader.ReadLine()
        if bytes == nil {
            break
        }
        fmt.Fprintln(w, string(bytes))
    }
}

func main() {
    Echo(os.Stdin, os.Stdout)
}</code>
登入後複製

更新測試案例

<code class="go">package main

import (
    "bufio"
    "bytes"
    "io"
    "os"
    "testing"
)

func TestEcho(t *testing.T) {
    input := "abc\n"
    reader := bytes.NewBufferString(input)
    writer := &bytes.Buffer{}

    Echo(reader, writer)

    actual := writer.String()
    if actual != input {
        t.Errorf("Wanted: %v, Got: %v", input, actual)
    }
}</code>
登入後複製

這個測試案例透過直接呼叫來模擬main 函數,並使用一個用於stdin 輸入的緩衝區和一個用於捕獲輸出的緩衝區。然後將捕獲的輸出與預期輸入進行比較,確保函數正確回顯輸入。

以上是如何測試從 Stdin 讀取的 Go 應用程式?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!