13

我将如何针对来自 fmt.Scan/Scanf/Scanln 的用户输入进行测试?

例如,我如何测试函数输入将接受来自 STDIN 的“4 5\n”和“1 2 3 4\n”并返回 n == 5 和数组 == [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)
}
4

2 回答 2

18

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

程序.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
于 2013-07-03T21:14:40.340 回答
-10

You can't. At least not so easily, such that, it would be worth the effort.

于 2013-07-03T21:00:07.550 回答