Testing in go, with go check

  2015-08-28


Disclaimer: this is mainly aimed at working as my self documentation.

Testing in go is fairly simple, as you can see in the docs A basic layout, a simple package:

A file named sample.go

package sample

func sampleFunction(sampleSlice []string) {
    sampleSlice = append(sampleSlice, "called")
}

In what go concerns this is a package and if you go build that it will compile. Adding testing to that package is as simple as adding a file ending in _test.go Anything with the aforementioned name will be interpreted as a test file and therefore only compiled at test time. For all practical purposes, during testing, your file will be considered part of the package whose name is declared in the package section of the _test.go. Sadly, this is as far as go helps us to make tests, if you read the docs you will find that there is no builtin toolset for things like assertions and suites.

To solve the shortcoming we can use go check Go check adds the possibility to have suites, asserts and a set of useful checks.

The way to hook go check into our existing test base is simple:

We first use the added concept of suites, which are found in the form of structs such as:

package sample

import (
    gc "gopkg.in/check.v1"
)

type aTestSuite struct {}

func (a *aTestSuite) TestingSomething(c *gc.C) {
    c.Assert(1, gc.Equals, 1)
}

A suite is a struct and its tests are all its methods whose name is prefixed with Test, additionally we have extra goodies such as Fixtures and other very nifty things (I encourage you to read the rest of the page).

To have one of these suites running you need to follow two simple steps. 1 - register the suite by calling: check.Suite() with a pointer to an instance of your suite. 2 - call the runner check.TestingT inside a function prefixed with Test which ensures us that it will be run by the test runner. A word of advice, only call TestingT once per binary no mather in which package or your full set of suites will run many times with possible unexpected results.

A finished example would look like:

package sample

import (
    "testing"

    gc "gopkg.in/check.v1"
)

func TestAll (t *testing.T) { // This could have any Test* name
    gc.TestingT(t)
}
type aTestSuite struct {}

var _ := gc.Suite(&aTestSuite{})

func (a *aTestSuite) TestingSomething(c *gc.C) {
    c.Assert(1, gc.Equals, 1)
}
comments powered by Disqus