Skip to content

Learning Go – Miniblog #8 – Unit Tests

January 14, 2013

This carries on from here, and started here.

The Go language system comes with what the documentation describes as a  "lightweight" unit testing framework. after trying to use it, I’d say it’s a bit too lightweight, for me at least.

In outline, it’s simple. Create Go source files in your package (see previous post) who’s names end with _test.go. Write ordinary Go code in these files to run your test, giving each function to be run a name that starts with Test. Then run the go command:

go test package

where "package" is the name of your package (csvsrv in my case).

This all works quite nicely except that the framework does not provide the simplest forms of tests. I’d really like to be able to say simple things like:

CHECK( HasCSVExt(  "foo.csv" ) )

and have the framework spit out a pass or fail message (OK, I can live without the pass messages). But it seems that something as easy as this (which all C and C++ testing frameworks supply) is "not good practice" in Go, or at least not possible. I ended up writing my own Check() function, but it’s a bit half-arsed:

package csvsrv
import "testing"

func Check( test bool, msg string, t *testing.T ) {
    if ( ! test ) {
        t.Errorf( msg )
    }
}

func Test_HasCSVExt( t *testing.T ) {
    Check( HasCSVExt( "foo.csv" ), "HasCVSExt (1)", t )
    Check( HasCSVExt( "foo.CSV" ), "HasCVSExt (2)", t )
    Check( ! HasCSVExt( "foo.crv" ), "HasCVSExt (3)", t )
    Check( ! HasCSVExt( "foo.csvx" ), "HasCVSExt (4)", t )
}

You can see that I have to supply a message and an identifying number, because the framework will always (correctly) report the error line as being in the Check function, and not identify the input that caused the error.

Anyway, enough moaning – it’s usable, if not very nice. When I ran the Go test command on this code, I got:

ok      csvsrv  0.132s

which I guess is the important thing…

From → golang

Leave a Comment

Leave a comment