如何在Go中针对用户输入编写测试

时间:2013-07-03 19:49:21

标签: input go

我如何测试来自fmt.Scan / Scanf / Scanln的用户输入?

例如,如何测试函数输入是否接受STDIN中的“4 5 \ n”和“1 2 3 4 \ n”并返回n == 5和array == [1,2,3,4 ]

package main

import (
    "fmt"
)

// input gets an array from the user.
func input() (m int, array []int) {
    fmt.Print("Enter the size of the array, n, and the difference, m: ")
    var n int
    _, err := fmt.Scanf("%d %d", &n, &m)
    if err != nil {
        panic(err)
    }

    fmt.Print("Enter the array as a space seperated string: ")
    array = make([]int, n)
    for i := 0; i < n; i++ {
        _, _ = fmt.Scan(&array[i])
    }

    return m, array
}

func main() {
    m, array := input()
    fmt.Println(m, array)
}

2 个答案:

答案 0 :(得分:14)

这是一个非常粗略的草案来说明原理。

program.go

package main

import (
    "fmt"
    "os"
)

// input gets an array from the user.
func input(in *os.File) (m int, array []int) {
    if in == nil {
        in = os.Stdin
    }

    fmt.Print("Enter the size of the array, n, and the difference, m: ")
    var n int
    _, err := fmt.Fscanf(in, "%d %d", &n, &m)
    if err != nil {
        panic(err)
    }

    fmt.Print("Enter the array as a space seperated string: ")
    array = make([]int, n)
    for i := 0; i < n; i++ {
        _, _ = fmt.Fscan(in, &array[i])
    }

    return m, array
}

func main() {
    m, array := input(nil)
    fmt.Println(m, array)
}

program_test.go

package main

import (
    "fmt"
    "io"
    "io/ioutil"
    "os"
    "testing"
)

func TestInput(t *testing.T) {
    var (
        n, m  int
        array []int
    )

    in, err := ioutil.TempFile("", "")
    if err != nil {
        t.Fatal(err)
    }
    defer in.Close()

    _, err = io.WriteString(in, "4 5\n"+"1 2 3 4\n")
    if err != nil {
        t.Fatal(err)
    }

    _, err = in.Seek(0, os.SEEK_SET)
    if err != nil {
        t.Fatal(err)
    }

    n, array = input(in)
    if n != 5 || fmt.Sprintf("%v", array) != fmt.Sprintf("%v", []int{1, 2, 3, 4}) {
        t.Error("unexpected results:", n, m, array)
    }
}

输出:

$ go test
ok      command-line-arguments  0.010s

答案 1 :(得分:-6)

你做不到。至少不那么容易,这样做是值得的。