我想编写包含对fmt.Scanf()
的调用的函数测试,但我在传递必需参数时遇到问题。
有更好的方法可以做到这一点,或者我需要模拟 fmt.Scanf()
此处给出了要测试的功能: https://github.com/apsdehal/Konsoole/blob/master/parser.go#L28
// 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
}
答案 0 :(得分:2)
理论上可以通过将Scanf
的值与其他os.Stdin
进行热交换来更改os.File
的行为。不过,我不会特别推荐它用于测试目的。
更好的选择就是让您Init
接收io.Reader
传递给Fscanf
。
但总的来说,尽可能将设备初始化代码与输入分开可能会更好。这可能意味着具有设备列表返回功能和设备打开功能。您只需要提示在实时/主要代码中进行选择。