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

前端 未结 2 1327
礼貌的吻别
礼貌的吻别 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: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()
    }
    

提交回复
热议问题