How can I write a Go test that writes to stdin?

前端 未结 2 1328
礼貌的吻别
礼貌的吻别 2021-01-13 00:34

Say that I have a simple application that reads lines from stdin and simply echoes it back to stdout. For example:

package main

import (
    \"bufio\"
    \         


        
相关标签:
2条回答
  • 2021-01-13 00:48

    Instead of doing everything in main with stdin and stdout, you can define a function that takes an io.Reader and an io.Writer as parameters and does whatever you want it to do. main could then call that function and your test function could test that function directly.

    0 讨论(0)
  • 2021-01-13 00:52

    Here is an example that writes to stdin and reads from stdout. Note that it does not work because the output contains "> " at first. Still, you can modify it to suit your needs.

    func TestInput(t *testing.T) {
        subproc := exec.Command("yourCmd")
        input := "abc\n"
        subproc.Stdin = strings.NewReader(input)
        output, _ := subproc.Output()
    
        if input != string(output) {
            t.Errorf("Wanted: %v, Got: %v", input, string(output))
        }
        subproc.Wait()
    }
    
    0 讨论(0)
提交回复
热议问题