普通网友 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 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,
  • ¥15 spaceclaim模型变灰色