测试在Go中使用fmt.Scanf()的函数

测试在Go中使用fmt.Scanf()的函数,go,Go,我想为函数编写一个测试,其中包括对fmt.Scanf()的调用,但我在将所需参数传递给函数时遇到问题 有更好的方法吗?或者我需要模拟fmt.Scanf() 此处给出了要测试的功能: 通过将os.Stdin的值与其他os.File进行热交换,理论上可以更改Scanf的行为。不过,我并不特别推荐它仅仅用于测试目的 更好的选择是让您的Init接收一个传递给Fscanf的io.Reader 然而,总的来说,最好尽可能地将设备初始化代码与输入分离开来。这可能意味着具有设备列表返回功能和设备打开功能。您只

我想为函数编写一个测试,其中包括对
fmt.Scanf()
的调用,但我在将所需参数传递给函数时遇到问题

有更好的方法吗?或者我需要模拟fmt.Scanf()

此处给出了要测试的功能:


通过将
os.Stdin
的值与其他
os.File
进行热交换,理论上可以更改
Scanf
的行为。不过,我并不特别推荐它仅仅用于测试目的

更好的选择是让您的
Init
接收一个传递给
Fscanf
io.Reader


然而,总的来说,最好尽可能地将设备初始化代码与输入分离开来。这可能意味着具有设备列表返回功能和设备打开功能。您只需要在live/main代码中提示选择。

所以您的确切意思是分离对scanf和其他类似函数的调用,以便我们可以轻松测试所有其他部分。是的,这可能是最好的。
// Initializes the network interface by finding all the available devices
// displays them to user and finally selects one of them as per the user
func Init() *pcap.Pcap {
    devices, err := pcap.Findalldevs()
    if err != nil {
        fmt.Fprintf(errWriter, "[-] Error, pcap failed to iniaitilize")
    }

    if len(devices) == 0 {
        fmt.Fprintf(errWriter, "[-] No devices found, quitting!")
        os.Exit(1)
    }

    fmt.Println("Select one of the devices:")
    var i int = 1
    for _, x := range devices {
        fmt.Println(i, x.Name)
        i++
    }

    var index int

    fmt.Scanf("%d", &index)

    handle, err := pcap.Openlive(devices[index-1].Name, 65535, true, 0)
    if err != nil {
        fmt.Fprintf(errWriter, "Konsoole: %s\n", err)
        errWriter.Flush()
    }
    return handle
}