Testing stdout in golang

Testing By Example

Intro

The other day I stumbled on the Example package for testing in golang and was amazed that I had not heard about it before now. If you write commnand line applications, sometimes it would be useful to test what your application is outputting to the console. This is where testing by Example from the golang toolbox is very useful.

https://blog.golang.org/examples

Sample Application code

Here is simple sample application:

package main

import "fmt"

func aFuncYouWantToTest() {
	fmt.Println("Hello World!!!")
}

func main() {
	aFuncYouWantToTest()
}

The Tests

so to test the output of this application we create a main_test.go file and in it we create a function called ExampleAFuncYouWantToTest the name must start with the word: Example so that it will trigger the testing package to run it. Then in what looks like a comment we place the word Output: which is an example of what should have been printed on stdout. If it does not it will generate a testing error with what was printed vs what was expected.

package main

func ExampleAFuncYouWantToTest() {
	aFuncYouWantToTest()

	// Output:
	// Hello World!!!
}

Mix it up with goroutines

package main

import (
	"fmt"
	"sync"
)

var wgApp sync.WaitGroup

func aFuncYouWantToTest(txt string) {
	fmt.Printf("Hello %s!!!\n", txt)
}

func setUp() {
	wgApp = sync.WaitGroup{}
	wgApp.Add(1)

	go func() {
		aFuncYouWantToTest("Paul")
		wgApp.Done()
	}()
	//time.Sleep(1000)
	aFuncYouWantToTest("Wowzers")

	wgApp.Wait()
}

func main() {
	setUp()
}

The Tests (redux)

package main

func ExampleAFuncYouWantToTest() {
	aFuncYouWantToTest("Paul")

	// Output:
	// Hello Paul!!!
}

func ExampleSetUp() {
	setUp()

	// Unordered output:
	// Hello Wowzers!!!
	// Hello Paul!!!
}

Conclusion

comments powered by Disqus