普通网友 2014-10-05 10:06
浏览 106
已采纳

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

I want to write test for function which includes a call to fmt.Scanf(), but I am having problem in passing the required parameter to function.

Is there a better way to do this or I need to mock fmt.Scanf()

Function to be tested is given here: 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
", err)
        errWriter.Flush()
    }
    return handle
}
  • 写回答

1条回答 默认 最新

  • dongyan6910 2014-10-05 10:27
    关注

    It's theoretically possible to change the behavior of Scanf by hotswapping the value of os.Stdin with some other os.File. I wouldn't particularly recommend it just for testing purposes, though.

    A better option would just be to make your Init take in an io.Reader that you pass to Fscanf.

    Overall, however, it would likely be better to separate your device initialization code from your input as much as possible. This probably means having a device list returning function and a device opening function. You only need to prompt for selection in live/main code.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序,怎么查看客户esp32板子上程序及烧录地址
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址