普通网友 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 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料
  • ¥15 使用R语言marginaleffects包进行边际效应图绘制