DEV Community

Discussion on: Unit testing Stdout in Go

Collapse
 
mstgnz profile image
Mesut GENEZ

So how do we capture print inside a void function that has no "writer" parameter?

func SayHello(name string) {
fmt.Print("Hi, my name is", name)
}

Collapse
 
reprintsev profile image
Aleksey Reprintsev

You can do it with example function from testing package:

func ExampleSayHello() {
    fmt.Println("Alex")
    // Output: Hi, my name is Alex"
}
Enter fullscreen mode Exit fullscreen mode

(btw, the result may be unexpected for your function: go.dev/play/p/J4zY09qEU4X )

Or use os.Pipe() as described in this discussion, but be aware of buffer overflows and data race.