Golang: testing terminal output

Golang: testing terminal output

This is short demonstration of testing Hello World! in the terminal.

When working with Go, we always strive to test, one thing we want to test, is the terminal output, this is a simple way for testing the standard output.

Testing the terminal output

// save copy of std out
old := os.Stdout
//create read and write pupe
r, w, _ := os.Pipe()
// set the stdout to the pipe
os.Stdout = w
// we excute the function
someFunctionCall()
// close the resource
w.Close()
// reset the stdout back to the orignal
os.Stdout = old
// read from the read pipe we create
got, _ := io.ReadAll(r)
// check if out is what you want
// want := something you want
//if got != want {
    // throw an error.
//}

Example

SayHello function

Given we have this example function, saying Hello World!, and we want to test this out, whether the terminal is properly printing it out.

func sayHello() {
    fmt.Printf("Hello World!")
}

The test we function

To test we apply the same method, and we test for strings equality.

func Test_SayHello(t *testing.T) {
    // save copy of std out
    old := os.Stdout
    //create read and write pupe
    r, w, _ := os.Pipe()
    // set the stdout to the pipe
    os.Stdout = w
    // we excuted
    sayHello()
    // close the resource
    w.Close()
    // reset the stdout back to the orignal
    os.Stdout = old
    // read from the read output we create
    out, _ := io.ReadAll(r)
    // convert to string
    got := string(out)
    // what we expect
    want := "Hello World!"
    if strings.Compare(got, want) != 0 {
        t.Errorf("incorrect hello got: %v", string(out))
    }
    if got != want {
        t.Errorf("incorrect hello got: %v", string(out))
    }
}