dongxianghui3709 2017-09-22 12:49
浏览 83
已采纳

填充os.Stdin以读取其中的函数

How do I fill os.Stdin in my test for a function that reads from it using a scanner?

I request a user command line input via a scanner using following function:

func userInput() error {
    scanner := bufio.NewScanner(os.Stdin)

    println("What is your name?")
    scanner.Scan()
    username = scanner.Text()

    /* ... */
}

Now how do I test this case and simulate a user input? Following example does not work. Stdin is still empty.

func TestUserInput(t *testing.T) {
    var file *os.File
    file.Write([]byte("Tom"))
    os.Stdin = file

    err := userInput()
    /* ... */
}
  • 写回答

1条回答 默认 最新

  • douyin7829 2017-09-22 13:07
    关注

    Mocking os.Stdin

    You're on the right track that os.Stdin is a variable (of type *os.File) which you can modify, you can assign a new value to it in tests.

    Simplest is to create a temporary file with the content you want to simulate as the input on os.Stdin. To create a temp file, use ioutil.TempFile(). Then write the content into it, and seek back to the beginning of the file. Now you can set it as os.Stdin and perform your tests. Don't forget to cleanup the temp file.

    I modified your userInput() to this:

    func userInput() error {
        scanner := bufio.NewScanner(os.Stdin)
    
        fmt.Println("What is your name?")
        var username string
        if scanner.Scan() {
            username = scanner.Text()
        }
        if err := scanner.Err(); err != nil {
            return err
        }
    
        fmt.Println("Entered:", username)
        return nil
    }
    

    And this is how you can test it:

    func TestUserInput(t *testing.T) {
        content := []byte("Tom")
        tmpfile, err := ioutil.TempFile("", "example")
        if err != nil {
            log.Fatal(err)
        }
    
        defer os.Remove(tmpfile.Name()) // clean up
    
        if _, err := tmpfile.Write(content); err != nil {
            log.Fatal(err)
        }
    
        if _, err := tmpfile.Seek(0, 0); err != nil {
            log.Fatal(err)
        }
    
        oldStdin := os.Stdin
        defer func() { os.Stdin = oldStdin }() // Restore original Stdin
    
        os.Stdin = tmpfile
        if err := userInput(); err != nil {
            t.Errorf("userInput failed: %v", err)
        }
    
        if err := tmpfile.Close(); err != nil {
            log.Fatal(err)
        }
    }
    

    Running the test, we see an output:

    What is your name?
    Entered: Tom
    PASS
    

    Also see related question about mocking the file system: Example code for testing the filesystem in Golang

    The easy, preferred way

    Also note that you can refactor userInput() to not read from os.Stdin, but instead it could receive an io.Reader to read from. This would make it more robust and a lot easier to test.

    In your app you can simply pass os.Stdin to it, and in tests you can pass any io.Reader to it created / prepared in the tests, e.g. using strings.NewReader(), bytes.NewBuffer() or bytes.NewBufferString().

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

报告相同问题?

悬赏问题

  • ¥15 mmocr的训练错误,结果全为0
  • ¥15 python的qt5界面
  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀