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().

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

报告相同问题?

悬赏问题

  • ¥20 谁能帮我挨个解读这个php语言编的代码什么意思?
  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面