2014-10-05 10:06 阅读 62


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!")

    fmt.Println("Select one of the devices:")
    var i int = 1
    for _, x := range devices {
        fmt.Println(i, x.Name)

    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)
    return handle
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    dongyan6910 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.

    点赞 评论 复制链接分享