2

I get confused when trying to write a test for simple console app in Golang. the function I want to test is very simple.

func SimpleFunc() {
    reader := bufio.NewReader(os.Stdin)
    output, _ := reader.ReadString('\n')
    fmt.Println(output)
}

Could you give an example how to write a test to mock stdin and stdout in Golang?

Thanks in advance

  • 3
    Stdin is just an `*os.File`, but it would be more flexible to just parameterize your functions to take any `io.Reader` – JimB Apr 06 '18 at 17:00
  • You can use `*bufio.Scanner` to abstract `io.Stdin` and `io.Writer` to abstract `io.Stdout` while passing them as dependencies to your struct, see Gist: https://gist.github.com/antonzhukov/2a6749f780b24f38b08c9916caa96663 and Playground: https://play.golang.org/p/BZMqpACupSc – Anton Zhukov Jul 14 '21 at 15:50

0 Answers0