首頁  >  文章  >  後端開發  >  如何測試從 Stdin 讀取的 Go 應用程式:模擬讀取器和寫入器指南

如何測試從 Stdin 讀取的 Go 應用程式:模擬讀取器和寫入器指南

Patricia Arquette
Patricia Arquette原創
2024-10-26 17:32:30882瀏覽

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中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn