我想为函数编写测试,其中包括对fmt.Scanf()
的调用,但在将必需参数传递给函数时遇到问题。
有更好的方法吗?或者我需要mockfmt.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: %sn", err)
errWriter.Flush()
}
return handle
}
理论上可以通过将os.Stdin
的值与其他os.File
热交换来改变Scanf
的行为。不过,我并不特别推荐它只是为了测试目的。
一个更好的选择是让你的Init
接受你传递给Fscanf
的io.Reader
。
然而,总的来说,最好尽可能地将设备初始化代码与输入分开。这可能意味着具有设备列表返回功能和设备打开功能。您只需要在live/main代码中提示选择即可。